-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray_to_list_functions.js
More file actions
72 lines (57 loc) · 1.83 KB
/
array_to_list_functions.js
File metadata and controls
72 lines (57 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Your code here.
function arrayToList(array1) { // converts an array into a list by looping over the array backwords and changing the list variable
var last = array1.length -1;
var list;
var i;
for (i = last; i >= 0; i--) {
list = {value: (array1[i]), rest: list};
}
return list;
}
function listToArray(list) { // converts a list into an array by looping over the list and pushing list.value into the array.
var node;
var array1 = [];
for (node = list; node; node = node.rest) { // navigating to the next list element is done by referring to the list.rest property.
array1.push(node.value);
}
return array1;
}
function prepend(element, next) { // this function gets the value and rest as arguments and creates a new list with them.
var list;
list = {
value: element,
rest: next
};
return list;
}
function nth(list, num) {
var node = list;
var i = 0;
while (node && i < num) { // the while loop gets two consecutive conditions. This resolves having to compare num with i at a later point.
node = node.rest;
i++;
}
if (!node) return undefined; // if there is no value in the position specified return undefined.
return node.value;
/*
for (; node && i < num; node = node.rest) {
for (node = list; node; node = node.rest) {
if (i === num) {
value = node.value;
console.log(list(20));
}
else {
i++;
}
}
return value;
*/
}
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, 40]), 1));
// → 20