Skip to content

Instantly share code, notes, and snippets.

@kamry-bowman
Last active December 28, 2018 01:18
Show Gist options
  • Save kamry-bowman/f6326bc38e1f40c28d6469316e1abf8c to your computer and use it in GitHub Desktop.
Save kamry-bowman/f6326bc38e1f40c28d6469316e1abf8c to your computer and use it in GitHub Desktop.
function arrayToList(arr) {
let list = {}
let pointer = list;
let end = arr.length - 1;
for (let i = 0; i < end; i++) {
let current = arr[i];
pointer.value = current;
pointer.rest = {};
pointer = pointer.rest;
}
pointer.value = arr[end];
pointer.rest = null;
return list;
}
function listToArray(list) {
if (list.rest === null) {
return [list.value];
}
const newArr = listToArray(list.rest);
newArr.unshift(list.value);
return newArr;
}
function listToArrayWhile(list) {
let arr = [];
let pointer = list;
while (pointer.rest !== null) {
arr.push(pointer.value);
pointer = pointer.rest;
}
arr.push(pointer.value);
return arr;
}
function prepend(elem, list) {
if (list.rest === null) {
list.rest = { value: elem, rest: null };
return { value: list.value, rest: {
value: elem,
rest: null,
}
};
}
return { value: list.value, rest: prepend(elem, list.rest) };
}
function nth(num, list) {
if (num === 0) {
return list;
}
return nth(num - 1, list.rest);
}
const list = arrayToList([1, 2, 3, 4, 5]);
console.log(list);
const arr = listToArrayWhile(list);
console.log(arr);
const longerList = (prepend(0, list));
console.log(longerList);
const third = nth(2, longerList);
console.log(third);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment