๐Ÿ’พarr.isMatrix

// ๐Ÿ”ธ arr.isMatrix
Object.defineProperty(Array.prototype, 'isMatrix', {
  get(){
    
    if (!this[0]) {
      console.log(`โ„น๏ธ array.isMatrix: array doesn't have first row. `);
      return false;
    }
    
    function valueIsArray(value, i){
      
      let isArray = Array.isArray(value);
      
      if (!isArray) {
        console.log(`โ„น๏ธ array.isMatrix: array[${i}] is not an array.`);
        return false;
      }
      
      return true;
    }
    
    // check if every value is an array.
    if (!this.every((value, i) => valueIsArray(value, i))) return false;
    
    // check if first row has elements
    if (!this[0].length > 0) {
      console.log(`โ„น๏ธ array.isMatrix: first row has no values.`);
      return false;
    }
    
    const arraySameLength = (array, i) => {
      
      const len = array.length;
      const len0 = this[0].length;
      
      if (len !== len0){
        console.log(`โ„น๏ธ array.isMatrix: array[${i}].length (${len}) โ‰  array[0].length (${len0}).`);
        return false
      }
      
      return true;
    }
    
    // check if every array has the same length;
    if (!this.every((arr, i) => arraySameLength(arr, i))) return false;
    
    return true;
  }
});

Last updated