Skip to content
Advertisement

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?

Advertisement

Answer

what is rest:list inside the list object?

It creates a property rest in the object literal, and assigns to it the value of the variable list – before assigning that object to the variable list. Notice that this happens in a loop, so what it does is to take the old value and overwrite it with a new value that references the old value.

Just what you need to build that nested list structure.

var list = null; // don't know why we make it null

That’s the initial value, which will be placed at the “end” of the list. If the array is empty, it will be returned, if the array has one element it will become the rest property of the object that is returned. If the array has more than one element…

why -1 on the length?

Because arrays are zero-indexed, i.e. their indices run from 0 to length-1. When we iterate backwards, we need this odd initial value and the i >= 0 comparison.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement