Skip to content

Instantly share code, notes, and snippets.

@sawant
Created September 2, 2014 13:26
Show Gist options
  • Save sawant/af5f2b119baf02448b39 to your computer and use it in GitHub Desktop.
Save sawant/af5f2b119baf02448b39 to your computer and use it in GitHub Desktop.
Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions 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, …
/*
http://eloquentjavascript.net/04_data.html
Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as argument, and write a listToArray function that produces an array from a list. Also write the helper functions 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, or undefined when there is no such element.
If you haven’t already, also write a recursive version of nth.
*/
function arrayToList( array ) {
var list = null;
for( i = array.length-1; i >= 0; i-- )
list = { value: array[i], rest: list };
return list;
}
function listToArray( list ) {
var array = [];
for( var node = list; node; node = node.rest )
array.push( node.value );
return array;
}
function prepend( value, rest ) {
return {value: value, rest: rest};
}
function nth( list, n ) {
// Simpler solution
//
// return listToArray( list )[n];
// Recursive solution
if( n === 0 )
return list.value;
else
return nth( list.rest, n - 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