-
Notifications
You must be signed in to change notification settings - Fork 2
/
list.js
98 lines (73 loc) · 1.87 KB
/
list.js
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict'
////////////////////////
// My way of doing it //
////////////////////////
// function arrayToList (array) {
// return {
// value: array.shift(),
// rest: array.length > 0 ? arrayToList(array) : null
// }
// }
///////////////////////////
// Their way of doing it //
///////////////////////////
function arrayToList(array) {
let list = null;
for (let i = array.length - 1; i >= 0; i--) {
list = {value: array[i], rest: list};
}
return list;
}
function listToArray (list) {
let array = [];
for (let node = list; node; node = node.rest) {
array.push(node.value);
}
return array;
}
/////////////////////
// My way of doing //
/////////////////////
function prepend (el, list) {
let array = listToArray(list);
array.unshift(el);
return arrayToList(array);
}
//////////////////////////////////////////////////////////////
// Their way of doing //
//////////////////////////////////////////////////////////////
/*
function prepend (el, list) {
return { value: el, rest: list};
}
*/
function nth (list, number) {
let array = listToArray(list);
return array[number];
}
///////////////////////////
// Their way of doing it //
///////////////////////////
function nth_r(list, n) {
if (!list) return undefined;
else if (n == 0) return list.value;
else return nth(list.rest, n - 1);
}
////////////////////////
// My way of doing it //
////////////////////////
/*function nth_r (list, number) {
if (number > 0 && list.rest) {
return nth_r(list.rest,--number);
}
else if (number === 0) {
return list.value;
}
}
*/
// console.log(arrayToList([10,20]));
// console.log(listToArray( arrayToList([10,20,30]) ));
console.log( prepend(40, arrayToList([10,20])) );
// console.log( nth(arrayToList([10,20,30]), 1) );
// console.log( nth(arrayToList([10,20,30]), 10) );
// console.log( nth_r(arrayToList([10,20,30,40,50]), 50) );