-
Notifications
You must be signed in to change notification settings - Fork 0
/
48-nesting-structure-comparison.js
36 lines (29 loc) · 1.09 KB
/
48-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
// Complete the function/method (depending on the language) to return true/True
// when its argument is an array that has the same nesting structure as the first array.
// For example:
// // should return true
// [ 1, 1, 1 ].sameStructureAs( [ 2, 2, 2 ] );
// [ 1, [ 1, 1 ] ].sameStructureAs( [ 2, [ 2, 2 ] ] );
// // should return false
// [ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2, 2 ], 2 ] );
// [ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2 ], 2 ] );
// // should return true
// [ [ [ ], [ ] ] ].sameStructureAs( [ [ [ ], [ ] ] ] );
// // should return false
// [ [ [ ], [ ] ] ].sameStructureAs( [ [ 1, 1 ] ] );
// For your convenience, there is already a function 'isArray(o)' declared and
// defined that returns true if its argument is an array, false otherwise.
Array.prototype.sameStructureAs = function (other) {
if (this.length !== other.length) {
return false;
}
return this.reduce((acc, e, i) => {
if (isArray(e) !== isArray(other[i])) {
return false;
}
if (!isArray(e) && !isArray(other[i])) {
return true;
}
return e.sameStructureAs(other[i]);
}, true);
};