|
| 1 | +Array.prototype.sameStructureAs = function (other) { |
| 2 | + /** |
| 3 | + * |
| 4 | + * @param {any[]} arr |
| 5 | + */ |
| 6 | + const mapStructure = ( |
| 7 | + arr, |
| 8 | + mappedDepth = { 0: { 0: 0 } }, |
| 9 | + elemNumber = 0, |
| 10 | + currentLevel = 0 |
| 11 | + ) => { |
| 12 | + for (let i = 0; i < arr.length; i++) { |
| 13 | + const eachelement = arr[i]; |
| 14 | + if (eachelement.constructor.name === "Array") { |
| 15 | + mapStructure(eachelement, mappedDepth, i, currentLevel + 1); |
| 16 | + } else if (elemNumber in mappedDepth) { |
| 17 | + if (currentLevel in mappedDepth[elemNumber]) { |
| 18 | + mappedDepth[elemNumber][currentLevel] += 1; |
| 19 | + } else { |
| 20 | + mappedDepth[elemNumber][currentLevel] = 1; |
| 21 | + } |
| 22 | + } else { |
| 23 | + mappedDepth[elemNumber] = {}; |
| 24 | + mappedDepth[elemNumber][currentLevel] = 1; |
| 25 | + } |
| 26 | + } |
| 27 | + return mappedDepth; |
| 28 | + }; |
| 29 | + if ( |
| 30 | + typeof other !== "object" || |
| 31 | + typeof this !== "object" || |
| 32 | + other.constructor.name !== "Array" || |
| 33 | + this.constructor.name !== "Array" |
| 34 | + ) { |
| 35 | + return false; |
| 36 | + } |
| 37 | + const mapStructureOther = mapStructure(other); |
| 38 | + const mapStructureThis = mapStructure(this); |
| 39 | + return JSON.stringify(mapStructureOther) === JSON.stringify(mapStructureThis); |
| 40 | +}; |
| 41 | + |
| 42 | +console.log([1, 1, 1].sameStructureAs([2, 2, 2]), "[1,1,1] same as [2,2,2]"); |
| 43 | + |
| 44 | +console.log( |
| 45 | + [1, [1, 1]].sameStructureAs([2, [2, 2]]) === true |
| 46 | + // "[1,[1,1]] same as [2,[2,2]]" |
| 47 | +); |
| 48 | +console.log( |
| 49 | + [(1, [1, 1])].sameStructureAs([[2, 2], 2]) === false |
| 50 | + // "[1,[1,1]] not same as [[2,2],2]" |
| 51 | +); |
| 52 | +console.log( |
| 53 | + [1, [1, 1]].sameStructureAs([2, [2]]) === false |
| 54 | + // "[1,[1,1]] not same as [2,[2]]" |
| 55 | +); |
| 56 | + |
| 57 | +console.log( |
| 58 | + [[[], []]].sameStructureAs([[[], []]]) === true |
| 59 | + // "[[[],[]]] same as [[[],[]]]" |
| 60 | +); |
| 61 | +console.log( |
| 62 | + [[[], []]].sameStructureAs([[1, 1]]) === false |
| 63 | + // "[[[],[]]] not same as [[1,1]]" |
| 64 | +); |
| 65 | + |
| 66 | +console.log([1, [[[1]]]].sameStructureAs([2, [[[2]]]]) === true); |
| 67 | +// , "[1,[[[1]]]] same as [2,[[[2]]]]"); |
| 68 | + |
| 69 | +console.log([].sameStructureAs(1) === false); |
| 70 | +// , "[] not same as 1"); |
| 71 | +console.log([].sameStructureAs({}) === false); |
| 72 | +// , "[] not same as {}"); |
| 73 | + |
| 74 | +console.log( |
| 75 | + [1, "[", "]"].sameStructureAs(["[", "]", 1]) === true |
| 76 | + // "[1,'[',']'] same as ['[',']',1]" |
| 77 | +); |
| 78 | + |
| 79 | +console.log([1, 2].sameStructureAs([[3], 3]) === false); |
| 80 | +// , "[1,2] not same as [[3],3]"); |
0 commit comments