I am working through the examples in Eloquent Javascript and I cannot seem to generate a working solution to recursively go from an array to a linked list.
The first (iterative) approach seems to work. I am stumped by the recursion. A push in the right direction would be greatly appreciated. Here is the code I have written so far:
function arrayToList(arr) {
var retObj = {};
var current = retObj;
for (var i = 0; i < arr.length; i++) {
current.value = arr[i];
if (arr[i + 1] === undefined) {
current.rest = null;
} else {
current.rest = {};
}
current = current.rest;
}
return retObj;
}
function recArrayToList(arr, obj) {
if (arr.length === 0) {
return 'DONE!';
}
obj.value = arr[0];
obj.rest = {};
return recArrayToList(arr.slice(1), obj.rest);
}
obj?objgives an empty object. @charleitfl:console.log(arrayToList([10, 20])); // → {value: 10, rest: {value: 20, rest: null}}(taken from Eloquent Javascript)