-
Notifications
You must be signed in to change notification settings - Fork 0
/
cap4.js
85 lines (68 loc) · 1.82 KB
/
cap4.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
//The sum of a range
range = (start, end) => {
let array = [];
for (let i = start; i <= end; i++) {
array.push(i);
}
return array;
}
sum = (array) => {
let result = 0;
//for (let value of array) or
for (let i = 0; i < array.length; i++) {
result += array[i];
}
return result;
}
console.log(sum(range(1 , 10)));
//Reversing an array
reverseArray = (array) => {
let output = [];
for (let i = array.length - 1; i >= 0; i--) {
output.push(array[i]);
}
return output;
}
reverseArrayInPlace = (array) => {
for (let i = 0; i < Math.floor(array.length / 2); i++) {
let old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
console.log(reverseArrayInPlace([2,3,6,5,55]))
//A list
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;
}
//Deep comparison
function deepEqual(a, b) {
if (a === b) return true;
if (a == null || typeof a != "object" ||
b == null || typeof b != "object") return false;
let keysA = Object.keys(a), keysB = Object.keys(b);
if (keysA.length != keysB.length) return false;
for (let key of keysA) {
if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
}
return true;
}
let obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true