Created
April 12, 2020 01:16
-
-
Save yitonghe00/640838f376e408db42efe163da6f2ea7 to your computer and use it in GitHub Desktop.
Excises of Eloquent JavaScript 4th edition. Chapter 04 Problem 03. https://eloquentjavascript.net/04_data.html#i_6xTmjj4Rf5
This file contains hidden or 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
// Your code here. | |
const arrayToList = (arr) => { | |
return arrayToListR(arr, 0); | |
} | |
const arrayToListR = (arr, start) => { | |
if (start >= arr.length) return null; | |
const ans = {}; | |
ans.value = arr[start]; | |
ans.rest = arrayToListR(arr, start + 1); | |
return ans; | |
} | |
const listToArray = (list) => { | |
const ans = []; | |
let curr = list; | |
while (curr) { | |
ans.push(curr.value); | |
curr = curr.rest; | |
} | |
return ans; | |
} | |
const prepend = (value, list) => { | |
const head = { | |
value, | |
rest: list | |
} | |
return head; | |
} | |
const nth = (list, index) => { | |
if (index == 0) return list.value; | |
return nth(list.rest, index - 1); | |
} | |
console.log(arrayToList([10, 20])); | |
// → {value: 10, rest: {value: 20, rest: null}} | |
console.log(listToArray(arrayToList([10, 20, 30]))); | |
// → [10, 20, 30] | |
console.log(prepend(10, prepend(20, null))); | |
// → {value: 10, rest: {value: 20, rest: null}} | |
console.log(nth(arrayToList([10, 20, 30]), 1)); | |
// → 20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment