Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zoolu-got-rhythm/6e727a69670ff9c73e0c1f41717bc2c2 to your computer and use it in GitHub Desktop.
Save zoolu-got-rhythm/6e727a69670ff9c73e0c1f41717bc2c2 to your computer and use it in GitHub Desktop.
function arrayToList(arr){
var prevList;
var ref;
for(var i = arr.length - 1; i >= 0; i--){
if(i === arr.length - 1){
ref = null;
}else{
ref = prevList;
}
var currentList = {value: arr[i], rest: ref};
prevList = currentList;
}
return prevList;
}
function listToArray(list){
var arr = [];
var currentObj = list;
// loop
while((currentObj.rest === null) || (currentObj.rest != null)){
// console.log(currentObj.rest === null); // f, f, f, t
arr.push(currentObj.value);
if(currentObj.rest != null){
currentObj = currentObj.rest;
}else{
break;
}
}
return arr;
}
function prepend(element, list){
return {value: element, rest: list};
}
function nth(list, index){
var currentList = list;
for(var i = 0; i < index; i++){
if(currentList.rest != null){
currentList = currentList.rest;
}else{
currentList.value = "undefined";
break;
}
}
return currentList.value;
}
//overload/write with a recursive version of nth
function nth(list, index){
if(index === 0){
return list.value;
}else if(list.rest === null){
return undefined;
}else{
return nth(list.rest, index - 1);
}
}
// this is a broken down valid recursion example that's functioning.
function nth(list, index){
if(index === 0){
return index;
}else{
console.log(index);
return nth(list, index - 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment