Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent Javascript Chapter 4: arrayToList/listToArray Execise

Question from eloquentjavascript:

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.

Can anyone explain this answer without any jargon? I can only learn by instructions.

Here is what I came up with for arrayToList: So start list null, create for loop decrementing and inside define "i" then return list.

function arrayToList(array){ //pass list as parameter
    var list = null; // don't know why we make it null
    for (var i=array.length-1; i>=0; i--)  // why -1 on the length?
        list = {value: array[i], rest:list}; //clueless
    return list;
}

what is rest:list inside the list object?


1 Answers

The last comment by @eloquent need to be modified:

var arr1 = [10, 20, 30];

function arrayToList(arr) {
  var list = {};

 for (var i = 0; i < arr.length; i++) {
    list.value = arr.splice(0, 1)[0];
    list.rest = (arr.length > 0) ? arrayToList(arr) : null;
 }

 return list;
}

console.clear();
console.log(  arrayToList(arr1) );
like image 152
Chekit Avatar answered Sep 19 '25 03:09

Chekit