Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Complete the method to return 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 ] ] );
- */
- Array.prototype.sameStructureAs = function (arr) {
- if(arr.length !== this.length) return false;
- for(let i = 0; i < arr.length; i++){
- if(Array.isArray(arr[i]) && Array.isArray(this[i])){
- if(!this[i].sameStructureAs(arr[i])) return false;
- continue;
- }
- if(Array.isArray(arr[i]) || Array.isArray(this[i])){
- 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
- console.log([ [ [ ], [ ] ] ].sameStructureAs( [ [ [ ], [ ] ] ] )); // true
- console.log([ [ [ ], [ ] ] ].sameStructureAs( [ [ 1, 1 ] ] )); // false
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement