Skip to content

Instantly share code, notes, and snippets.

@gitfaf
Created August 17, 2017 18:49
Show Gist options
  • Save gitfaf/f413086d093f45d2ef305a1cd48fbcda to your computer and use it in GitHub Desktop.
Save gitfaf/f413086d093f45d2ef305a1cd48fbcda to your computer and use it in GitHub Desktop.
A list exercise from Eloquent JS
function List (value, rest) {
this.value = value;
this.rest = rest || null;
}
function arrayToList (array) {
if (!array) return null;
let list = new List(array[0], null);
let tmp = list;
for (let i = 1, len = array.length; i < len; i++) {
tmp.rest = new List(array[i], null);
tmp = tmp.rest;
}
return list;
}
console.log(arrayToList([1, 2, 3]));
function listToArray (list) {
let out = [];
let tmp = list;
while (tmp.rest !== null) {
out.push(tmp.value);
tmp = tmp.rest;
}
return out;
}
console.log('array:',[1, 2, 3, 4, 5],
'arrayToList([1, 2, 3, 4, 5]):', arrayToList([1, 2, 3, 4, 5]),
'listToArray(arrayToList([1, 2, 3, 4, 5])):', listToArray(arrayToList([1, 2, 3, 4, 5])));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment