I am working on a class constructor overload where I need to recursively invoke the constructor based on the provided arguments.
class Matrix {
/**
* Construct a new Matrix using the given entries.
* @param arr the matrix entries
*/
constructor(arr?: number[][]);
/**
* Construct a new Matrix with specified size.
* @param rows the number of rows in the matrix
* @param cols the number of columns in the matrix
*/
constructor(rows?: number, cols?: number);
constructor(rows: number[][]|number = 0, cols: number = 0) {
function isMatrixRaw(m: any): m is number[][] {
// validate if m is a 2D array of numbers
}
if (isMatrixRaw(rows)) {
// perform main operations here
} else {
let m: number[][];
// create a 2D array based on rows and cols
// make a recursive call to the constructor with the new 2D array
new Matrix(m) // Is this correct?
}
}
}
The primary task of the constructor is completed when the argument is a 2-dimensional array of entries. However, an additional overload is needed for providing row and column sizes (e.g., new Matrix(2,3)
). If both rows
and cols
are numbers, I intend to generate a 2-dimensional array and then pass it back into the constructor.
How do recursive constructor calls function in TypeScript? Should I use new Matrix()
, return new Matrix()
, this.constructor()
, Matrix.constructor()
, or another approach?