💾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;
}
});
let a = [ [1, 2, 3], [4, 4, 6], ];
let b = [ [1, 2, 3], [4, 6], ];
let c = [ "[1, 2, 3]", [4, 6], ];
let d = [];
let e = [[]];
;[
a, // true
b, // false: array[1].length (2) ≠ array[0].length (3)
c, // false: array[0] is not an array
d, // false: doesn't have first row
e, // false: first row has no values
].forEach(x => console.log(x.isMatrix));
helpers for Google Apps Script - 可用來檢查 2D data 資料格式是否正確
Last updated