Skip to content

Instantly share code, notes, and snippets.

@drewhoener
Last active February 7, 2019 22:11
Show Gist options
  • Save drewhoener/3df5a2a7be35902fa6cc62813e6e5527 to your computer and use it in GitHub Desktop.
Save drewhoener/3df5a2a7be35902fa6cc62813e6e5527 to your computer and use it in GitHub Desktop.
const arrayToList = (arr) => {
let head = {};
let list = head;
for(let i = 0; i < arr.length; i++){
list.val = arr[i];
list.rest = {};
list = list.rest;
}
return list;
}
const listToArray = (list) => {
let workingList = list;
let arr = [];
while(list.value != null){
arr.push(list.value);
workingList = workingList.rest;
}
return arr;
}
const prepend = (list, val) => {
return {
value: val,
rest: list
};
}
const nth = (list, index) => {
let workingList = list;
if(index < 0)
return undefined;
let cur = 0;
while(cur < index){
if(workingList == null)
return undefined;
workingList = workingList.rest;
cur++;
}
if(workingList == null || workingList.value == null)
return undefined;
return list.value;
}
const recurNth = (list, index, curIndex) => {
if(list == null)
return undefined;
if(index == curIndex){
if(list.value == null)
return undefined;
return list.value;
}
return recurNth(list.rest, index, curIndex + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment