Advertisement
CSenshi

t2

Oct 6th, 2023
700
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Complete the method to return true when its argument is an array
  3. that has the same nesting structures and same corresponding
  4. length of nested arrays as the first array.
  5.  
  6. For example:
  7.  // should return true
  8. [ 1, 1, 1 ].sameStructureAs( [ 2, 2, 2 ] );          
  9. [ 1, [ 1, 1 ] ].sameStructureAs( [ 2, [ 2, 2 ] ] );  
  10.  
  11.  // should return false
  12. [ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2, 2 ], 2 ] );  
  13. [ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2 ], 2 ] );  
  14.  
  15. // should return true
  16. [ [ [ ], [ ] ] ].sameStructureAs( [ [ [ ], [ ] ] ] );
  17.  
  18. // should return false
  19. [ [ [ ], [ ] ] ].sameStructureAs( [ [ 1, 1 ] ] );
  20. */
  21.  
  22. Array.prototype.sameStructureAs = function (arr) {
  23.   if(arr.length !== this.length) return false;
  24.  
  25.   for(let i = 0; i < arr.length; i++){
  26.     if(Array.isArray(arr[i]) && Array.isArray(this[i])){
  27.       if(!this[i].sameStructureAs(arr[i])) return false;
  28.       continue;
  29.     }
  30.    
  31.     if(Array.isArray(arr[i]) || Array.isArray(this[i])){
  32.       return false;
  33.     }
  34.   }
  35.  
  36.   return true;
  37. }
  38.  
  39.  
  40. console.log([ 1, 1, 1 ].sameStructureAs( [ 2, 2, 2 ] )); // true
  41. console.log([ 1, [ 1, 1 ] ].sameStructureAs( [ 2, [ 2, 2 ] ] )); // true
  42. console.log([ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2, 2 ], 2 ] ));  // false
  43. console.log([ 1, [ 1, 1 ] ].sameStructureAs( [ [ 2 ], 2 ] ));  // false
  44. console.log([ [ [ ], [ ] ] ].sameStructureAs( [ [ [ ], [ ] ] ] )); // true
  45. console.log([ [ [ ], [ ] ] ].sameStructureAs( [ [ 1, 1 ] ] )); // false
  46.  
  47.  
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement