Skip to content

Instantly share code, notes, and snippets.

@TimBlock
Created January 14, 2016 16:39
Show Gist options
  • Select an option

  • Save TimBlock/40ab9af72aea5612189b to your computer and use it in GitHub Desktop.

Select an option

Save TimBlock/40ab9af72aea5612189b to your computer and use it in GitHub Desktop.
// Your code here.
function arrayToList(arr){
var list = null;
for (var i = arr.length-1; i>=0; i--)
list = {value:arr[i], rest:list};
return list;
}
function listToArray(list){
var arr=[];
for (var node = list; node; node = node.rest)
arr.push(node.value);
return arr;
}
function prepend(value, list) {
return {value: 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment