Nodejs Array Same Structure sameStructureAs(a2)

Here you can find the source of sameStructureAs(a2)

Method Source Code

Array.prototype.sameStructureAs = function(a2) {
  let isSame = true;// w w w. j a  v a  2  s  . c o  m
  (function recurse(arr1, arr2){
    if (!arr1 || !arr2) {
      isSame = false;
      return;
    }
    if (arr1.length !== arr2.length) {
      isSame = false;
      return;
    }
    arr1.forEach((el, i) => {
      if (Array.isArray(el)) {
        if (Array.isArray(arr2[i])) {
          recurse(el, arr2[i]);
        } else {
          isSame = false;
        }
      }
    });
  })(this, a2);
  return isSame;
}

// Can't use arrow function, this binds to an empty obj

Related

  1. sameStructureAs(other)
    Array.prototype.sameStructureAs = function (other) {
      const stringify = a => `[${a.map(b => Array.isArray(b) ? stringify(b) : '|').join('')}]`
      return Array.isArray(other) ? stringify(this) === stringify(other) : false
    
  2. sameStructureAs(other)
    Array.prototype.sameStructureAs = function (other) {
      if ( this.length !== other.length ) return false;
      for ( var i = 0; i < this.length; i++ ){
        if (Array.isArray(this[i]) && Array.isArray(other[i])) {
          if (!this[i].sameStructureAs(other[i])) return false;
        } else if (Array.isArray(this[i]) || Array.isArray(other[i])){
          return false;
      return true;
    };
    
  3. sameStructureAs(other)
    Array.prototype.sameStructureAs = function (other) {
      var helper = function(a,b){
        if(!isArray(b))
          return false;
        for(i in a){
          if(b[i]===undefined || isArray(a[i])!==isArray(b[i]) || isArray(a[i]) && !a[i].sameStructureAs(b[i]))
            return false;
        return true;
    ...
    
  4. sameStructureAs(other)
    Array.prototype.sameStructureAs = function (other) {   
      if (!Array.isArray(other)) return false;
      function transform(array) {
        return array.map(item => Array.isArray(item) ? [transform(item)] : "0");
      return JSON.stringify(transform(this)) === JSON.stringify(transform(other));
    };
    console.log([ 1, [ 1, 1 ] ].sameStructureAs( [ 2, [ 2, 2 ] ] ));
    console.log([ [ [ ], [ ] ] ].sameStructureAs( [ [ [ ], [ ] ] ] ))
    ...