-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
nesting-structure-comparison.js
48 lines (40 loc) · 1.46 KB
/
nesting-structure-comparison.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
// Return 'true' if and only if 'other' has the same
// nesting structure as 'this'.
function isArray(array) {
return array.constructor === Array;
}
// Note: You are given a function isArray(o) that returns
// whether its argument is an array.
Array.prototype.sameStructureAs = function (other) {
if (!isArray(other)) return false;
if (this.length != other.length) return false;
for (let i = 0; i < this.length; i++) {
const element = this[i];
const otherElement = other[i];
if (isArray(element) && !element.sameStructureAs(otherElement)) {
return false;
} else if (!isArray(element) && isArray(otherElement)) {
return false;
}
}
return true;
};
// Note: You are given a function isArray(o) that returns
// whether its argument is an array.
Array.prototype.sameStructureAs = function (other) {
if (!isArray(other)) return false;
if (this.length != other.length) return false;
return this.every((element, i) => {
const otherElement = other[i];
if (isArray(element) && !element.sameStructureAs(otherElement)) {
return false;
} else if (!isArray(element) && isArray(otherElement)) {
return false;
}
return true;
});
};
console.log([ 1, 1, 1 ].sameStructureAs( [ 2, 2, 2 ] )); // true
console.log([ 1, [ 1, 1 ] ].sameStructureAs( [ 2, [ 2, 2 ] ] )); // true
console.log([ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2, 2 ], 2 ] )); // false
console.log([ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2 ], 2 ] )); // false