Scenario
I have the following piece of code:
const composeMatrix = (nRow, nCol, filler) => Array(nRow).fill(Array(nCol).fill(filler));
class Matrix extends Array {
constructor({ nRows = 3, nCols = 3, filler = 0 } = {}) {
super(...composeMatrix(nRows, nCols, filler));
}
makeTranspose() {
const mat = this;
const column = mat[0];
return column.map((_, i) => {
return mat.map((row) => row[i]);
});
}
}
I'm instantiating a new Matrix like this:
const mat = new Matrix({ nRows: 4, filler: 1 });
Logging mat to the console gives me as expected,
Matrix(4) [
[ 1, 1, 1 ],
[ 1, 1, 1 ],
[ 1, 1, 1 ],
[ 1, 1, 1 ]
]
Problem
Now when I call the makeTranspose method of the class, it returns me this:
[
Matrix(4) [ 1, 1, 1, 1 ],
Matrix(4) [ 1, 1, 1, 1 ],
Matrix(4) [ 1, 1, 1, 1 ]
]
Expected output:
Matrix(3) [
[ 1, 1, 1, 1 ],
[ 1, 1, 1, 1 ],
[ 1, 1, 1, 1 ]
]
What I figured is, the map function calls the constructor of this subclass every time while iterating through the array, which in turn calls super, which then calls the composeMatrix function and a new Matrix gets made.
How can I fix this?
- I want a
classto extendArraywith some added methods. - The constructor needs to take some relevant parameters and function as expected.
- I don't want to add functions to the
prototype.