Skip to content

Instantly share code, notes, and snippets.

@jonurry
Last active July 17, 2022 10:57
Show Gist options
  • Save jonurry/9ceb8e580072fdd4d9d58bb2a9edc5da to your computer and use it in GitHub Desktop.
Save jonurry/9ceb8e580072fdd4d9d58bb2a9edc5da to your computer and use it in GitHub Desktop.
4.3 A List (Eloquent JavaScript Solutions)
function arrayToList(array) {
let result = {};
if (Array.isArray(array)) {
let currListItem = result;
for (let item of array) {
let newListItem = {
value: item,
rest: null
};
if (typeof currListItem.rest === 'undefined') {
result = newListItem;
} else {
currListItem.rest = newListItem;
}
currListItem = newListItem;
}
}
return result;
}
function listToArray(list) {
let result = [];
if (typeof list === 'undefined' || list.value === undefined || list.rest === undefined) {
return result;
} else {
result.push(list.value);
while (list.hasOwnProperty('rest') && list.rest !== null) {
list = list.rest;
if (list.hasOwnProperty('value')) {
result.push(list.value);
}
}
}
return result;
}
function prepend(element, list) {
return {
value: element,
rest: list
};
}
function nth(list, number) {
return listToArray(list)[number];
}
function nthRecursive(list, number) {
if (number === 0) {
return list.value;
} else if (list.rest === null) {
return undefined;
} else {
return nthRecursive(list.rest, number-1);
}
}
console.log(arrayToList());
console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(arrayToList([4, 3, 2, 1]));
// → {value: 4, rest: {value: 3, rest: {value: 2, rest: {value: 1, rest: null}}}}
console.log(listToArray());
// → []
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]
console.log(listToArray({value: 10, rest: {xxx: 20, yyy: null}}));
// → [10]
console.log(listToArray({value: 10, rest: {value: 20, yyy: null}}));
// → [10, 20]
console.log(listToArray({value: 10, rest: {xxx: 20, rest: null}}));
// → [10]
console.log(prepend(10, prepend(20, null)));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(nth(arrayToList([10, 20, 30]), 1));
// → 20
console.log(nth(arrayToList([10, 20, 30]), 3));
// → undefined
console.log(nth(arrayToList([10, 20, 30]), -2));
// → undefined
console.log(nthRecursive(arrayToList([10, 20, 30]), 1));
// → 20
console.log(nthRecursive(arrayToList([10, 20, 30]), 3));
// → undefined
console.log(nthRecursive(arrayToList([10, 20, 30]), -2));
// → undefined
// now with the help of the hints...
function arrayToListWithHints(array) {
let result = {};
if (Array.isArray(array)) {
let list = null;
array = array.reverse();
for (let item of array) {
list = {
value: item,
rest: list
};
}
result = list;
}
return result;
}
function listToArrayWithHints(list) {
let result = [];
if (typeof list === 'undefined' || list.value === undefined || list.rest === undefined) {
return result;
} else {
for (let node = list; node; node = node.rest) {
if (node.hasOwnProperty('value')) {
result.push(node.value);
}
}
}
return result;
}
console.log('\nWith Hints:');
console.log(arrayToListWithHints());
console.log(arrayToListWithHints([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(arrayToListWithHints([4, 3, 2, 1]));
// → {value: 4, rest: {value: 3, rest: {value: 2, rest: {value: 1, rest: null}}}}
console.log(listToArrayWithHints());
// → []
console.log(listToArrayWithHints(arrayToListWithHints([10, 20, 30])));
// → [10, 20, 30]
console.log(listToArrayWithHints({value: 10, rest: {xxx: 20, yyy: null}}));
// → [10]
console.log(listToArrayWithHints({value: 10, rest: {value: 20, yyy: null}}));
// → [10, 20]
console.log(listToArrayWithHints({value: 10, rest: {xxx: 20, rest: null}}));
// → [10]
console.log(nth(arrayToListWithHints([10, 20, 30]), 1));
// → 20
console.log(nth(arrayToListWithHints([10, 20, 30]), 3));
// → undefined
console.log(nth(arrayToListWithHints([10, 20, 30]), -2));
// → undefined
@jonurry
Copy link
Author

jonurry commented Feb 7, 2018

4.3 A list

Objects, as generic blobs of values, can be used to build all sorts of data structures. A common data structure is the list (not to be confused with array). A list is a nested set of objects, with the first object holding a reference to the second, the second to the third, and so on.

let list = {
  value: 1,
  rest: {
    value: 2,
    rest: {
      value: 3,
      rest: null
    }
  }
};

The resulting objects form a chain.

A nice thing about lists is that they can share parts of their structure. For example, if I create two new values {value: 0, rest: list} and {value: -1, rest: list} (with list referring to the binding defined earlier), they are both independent lists, but they share the structure that makes up their last three elements. In addition, the original list is also still a valid three-element list.

Write a function arrayToList that builds up a data structure like the previous one when given [1, 2, 3] as the 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.

@jonurry
Copy link
Author

jonurry commented Feb 16, 2018

Hints

Building up a list is easier when done back to front. So arrayToList could iterate over the array backward (see the previous exercise) and, for each element, add an object to the list. You can use a local binding to hold the part of the list that was built so far and use an assignment like list = {value: X, rest: list} to add an element.

To run over a list (in listToArray and nth), a for loop specification like this can be used:

for (let node = list; node; node = node.rest) {}

Can you see how that works? Every iteration of the loop, node points to the current sublist, and the body can read its value property to get the current element. At the end of an iteration, node moves to the next sublist. When that is null, we have reached the end of the list and the loop is finished.

The recursive version of nth will, similarly, look at an ever smaller part of the “tail” of the list and at the same time count down the index until it reaches zero, at which point it can return the value property of the node it is looking at. To get the zeroeth element of a list, you simply take the value property of its head node. To get element N + 1, you take the _N_th element of the list that’s in this list’s rest property.

@PiotrNap
Copy link

PiotrNap commented Jul 5, 2020

Hey Jonurry, thanks for those solutions! I was scratching my head around to try to solve these ones.
I was wondering why did you put the first '=== undefined' (on lines 23 and 109), between semicolons, while the other ones not. Is there any specific reason for it? Or it is just your personal preference?

@jonurry
Copy link
Author

jonurry commented Jul 6, 2020

Hey @PiotrNap. Glad it helped you.
The reason that the first undefined is in single quotes is because typeof returns a string value so the comparison has to be a string as well.

@PiotrNap
Copy link

PiotrNap commented Jul 6, 2020

Alright, that makes sense ! Ty for answering :)

@tuan185
Copy link

tuan185 commented Jul 25, 2021

Hello Jonurry, I'm a newbie in js so I have some questions about your solutions. I hope you can help me.

In arrayToList function, I don't know how the value of "result" changes in the loop. In your loop, the "result" only appears in the if (typeof currListItem.rest === 'undefined') but when I try testing it like this :

if (typeof currListItem.rest === 'undefined') {
result = newListItem;
console.log(true)
} else {
currListItem.rest = newListItem;
console.log(false)
}

The if (typeof currListItem.rest === 'undefined') only works in the first time, so I don't know how the "result" can change its value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment