// Array.prototype + .max(), .maxRowLength (by Object.assign)
Object.assign(Array.prototype, {
// max something in the array
max(mapf = (x) => x) {
// -----------------------------------------
return Math.max(...this.map(x => mapf(x)));
// ^^^^^^^^
// ⛔ TypeError: this.map is not a function
// -----------------------------------------
},
// max row length of the matrix
get maxRowLength() {
return this.max(row => row.length);
},
});
// matrix (2D array)
let m = [[1, 2, 3, 4], [1, 2], [1, 2, 3]];
m.max(row => row.length)
m.maxRowLength
// ------------------------------------------------------------
// ⭐ `Object.assign()` copies with "get/set" operations, so if
// • source object has a getter method, or
// • target object has a setter method
// ⭐ they will be INVOKED❗, NOT COPIED❗.
// ------------------------------------------------------------
// the "source" object
let s = {
// ⭐ function copied ✅
max(mapf = (x) => x) {
return Math.max(...this.map(x => mapf(x)));
// ^^^^^^^^
// ⛔ TypeError: this.map is not a function
},
// ⭐ getter invoked❗, NOT COPIED❗(during the assign❗)
get maxRowLength() {
return this.max(row => row.length);
},
};
// ⭐ during `Object.assign`:
// ---------------------------------------------
// (function copied ✅)
// • t.max = t.max
//
// (source getter invoked❗, NOT COPIED❗)
// • t.maxRowLength = s.maxRowLength
// ╰⭐ getter invoked ╯
//
// => return this.max(...) // ⭐ this === s
// => return Math.max(...this.map(...)) // ⛔ `s.map` is not a function
// ^^^^^^^^
// ⛔ TypeError: this.map is not a function
let t = Object.assign(Array.prototype, s); // the "target" object
// matrix
let m = [[1, 2, 3, 4], [1, 2], [1, 2, 3]]; // can't even reach here!
// max something in the array
function arrayMax(arr, mapf = x => x){
return Math.max(...arr.map(x => mapf(x)));
}
// max row length of the 2D array
// assuming an element in the 2D array is called a "row".
function maxRowLength(matrix){
return arrayMax(matrix, row => row.length);
}
// 2D array
let m = [[1, 2, 3, 4], [1, 2], [1, 2, 3]];
arrayMax(m, row => row.length) // 4 ✅
maxRowLength(m) // 4 ✅