Last active
May 3, 2018 14:35
-
-
Save Luke-Rogerson/fbb03e5c0dff2cc81c1a4d9cae70eba8 to your computer and use it in GitHub Desktop.
AList - Eloquent Javascript, Chapter 4 - https://repl.it/@Luke_Rogerson/AList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
let list = { | |
value: 1, | |
rest: { | |
value: 2, | |
rest: { | |
value: 3, | |
rest: null | |
} | |
} | |
}; | |
*/ | |
/* Write a function arrayToList that builds up a list structure like the one shown when given [1, 2, 3] as argument. Also write a listToArray function that produces an array from a list. Then add a helper function prepend, which takes an element and a list and creates a new list that adds the element to the front of the input list, and nth, which takes a list and a number and returns the element at the given position in the list (with zero referring to the first element) or undefined when there is no such element. */ | |
function arraytoList () { | |
const array = [1,2,3]; | |
let list; | |
for (let x = array.length-1; x >= 0; x--) { | |
list = {value: array[x], rest:list}; | |
} | |
return list; | |
} | |
function listToArray(list) { | |
let newArray = []; | |
for (let node = list; node; node = node.rest) { | |
newArray.push(list.value); | |
list = list.rest; | |
} | |
return newArray; | |
} | |
function helper () { | |
for (let node = lits; node; node= node.rest) { | |
} | |
} | |
listToArray(arraytoList()); | |
// Still need to implement prepend and nth functions. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment