I was trying to extend Array.prototype with some new methods/properties, the following is what I did in the first attempt, which ended up with a TypeError:
// 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 2D array
// assuming an element of the 2D array is called a "row"
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) // didn't work, can't even run.
m.maxRowLength
I don't understand why this is happening, so I go on with my second attempt, this time with a different approach, and it runs successfully without any problem:
// Array.prototype + .max()
Array.prototype.max = function(f = x => x){
return Math.max(...this.map(x => f(x)));
};
// Array.prototype + .maxRowLength (by Object.defineProperty)
Object.defineProperty(Array.prototype, 'maxRowLength', {
get: function(){ return this.max(row => row.length) }
});
// matrix (2D array)
let m = [[1, 2, 3, 4], [1, 2], [1, 2, 3]]; // 3 "rows"
m.max(row => row.length) // 4 ✅
m.maxRowLength // 4 ✅
Does anyone know what are the differences between these two approaches, and most importantly why the first attampt failed?