-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnesting_structure_comparison.js
61 lines (46 loc) · 1.67 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
49
50
51
52
53
54
55
56
57
58
59
// Complete the function/method (depending on the language) to return true/True when its argument is an array that has the same nesting structures and same corresponding length of nested arrays 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.
// -------------------- My Solution -----------------------------------
function isArray(o) {
if (Array.isArray(o)) {
return true
}
else
{
return false
}
}
Array.prototype.sameStructureAs = function (other) {
if (this.length == other.length) {
for (let i = 0; i < this.length; i++) {
let arrayAElementCheck = isArray(this[i])
let arrayBElementCheck = isArray(other[i])
if (arrayAElementCheck == arrayBElementCheck ){
if (arrayAElementCheck == true) {
return this[i].sameStructureAs(other[i])
}
else {
continue
}
}
else {
return false
}
}
return true
}
else {
return false
}
};