/*
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.
*/
function arrayToList(array){
var savedArray = array.slice();
var element = {value:savedArray.shift()};
var ele = element;
while(savedArray.length){
ele.rest = {value:savedArray.shift()}
ele = ele.rest;
}
return element;
}
var prepend = function(element,list){
return {value:element,rest:list};
};
var list = {
value: 1,
rest: {
value: 2,
rest: {
value: 3,
rest: null
}
}
};
function listToArray(list){
var array = [];
console.log(list);
for (var node = list; node; node = node.rest) {
array.push(node.value);
}
return array;
}
console.log(listToArray(prepend(0,list)));
var list2 = arrayToList([1,2,3]);
//list2 = list;
console.log(listToArray(list2));
//console.log(list2);
//console.log(list == list2);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.