Created
August 17, 2017 18:49
-
-
Save gitfaf/f413086d093f45d2ef305a1cd48fbcda to your computer and use it in GitHub Desktop.
A list exercise from Eloquent JS
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
function List (value, rest) { | |
this.value = value; | |
this.rest = rest || null; | |
} | |
function arrayToList (array) { | |
if (!array) return null; | |
let list = new List(array[0], null); | |
let tmp = list; | |
for (let i = 1, len = array.length; i < len; i++) { | |
tmp.rest = new List(array[i], null); | |
tmp = tmp.rest; | |
} | |
return list; | |
} | |
console.log(arrayToList([1, 2, 3])); | |
function listToArray (list) { | |
let out = []; | |
let tmp = list; | |
while (tmp.rest !== null) { | |
out.push(tmp.value); | |
tmp = tmp.rest; | |
} | |
return out; | |
} | |
console.log('array:',[1, 2, 3, 4, 5], | |
'arrayToList([1, 2, 3, 4, 5]):', arrayToList([1, 2, 3, 4, 5]), | |
'listToArray(arrayToList([1, 2, 3, 4, 5])):', listToArray(arrayToList([1, 2, 3, 4, 5]))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment