Hello, apparently I got stuck on Chapter 4.3 A list
Here’s the full working code for reference:
function arrayToList(array) {
let list = null;
for (let i = array.length - 1; i >= 0; i--) {
list = {value: array[i], rest: list};
}
return list;
}
function listToArray(list) {
let array = [];
for (let node = list; node; node = node.rest) {
array.push(node.value);
}
return array;
}
function prepend(value, list) {
return {value, rest: list};
}
function nth(list, n) {
if (!list) return undefined;
else if (n == 0) return list.value;
else return nth(list.rest, n - 1);
}
console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]
console.log(prepend(10, prepend(20, null)));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(nth(arrayToList([10, 20, 30]), 1));
// → 20
I reviewed the arrayToList
function, already. I understood it fine.
I’m currently reviewing the listToArray
function and this is what I’m confused about:
(let node = list; node; node = node.rest)
What exactly is going on on this for loop? I don’t understand the condition.
Thanks for the help! I’m coming back on the same thread if I still don’t understand something on the solution, if you don’t mind