I would like some help on making my solution more functional. At present, I rely heavily on using indexes in my map functions. I am also seeking general feedback and advice, thanks.
export const getMatrixColumns = (a: number[][]) => {
return a[0].length;
};
export const getMatrixRows = (a: number[][]) => {
return a.length;
};
export const matricesAreValid = (a: number[][], b: number[][]) => {
return getMatrixColumns(a) === getMatrixRows(b);
};
export const generateEmptyMatrix = (rows: number, cols: number) => {
return [...Array(rows)].fill(0).map(() => [...Array(cols)].fill(0));
};
export const dotProduct = (a: number[], b: number[]) => {
return a.map((value, i) => value * b[i]).reduce((acc, val) => acc + val, 0);
};
export const multiplyMatrices = (a: number[][], b: number[][]) => {
if (matricesAreValid(a, b)) {
const rows = getMatrixRows(a);
const cols = getMatrixColumns(b);
return generateEmptyMatrix(rows, cols).map((resultRow, i) =>
resultRow.map((element: number, j: number) => {
const column = b.map(row => row[j]);
const row = a[i];
return dotProduct(row, column);
})
);
}
};
1 Answer 1
Concise Function Body
The function body of an arrow function can be concise.
For instance can getMatrixColumns
shorten to
export const getMatrixColumns = (a: number[][]) => a[0].length;
Method Name
The method names getMatrixColumns
and getMatrixRows
let me expect that the the methods return a number[]
instead of a number
.
A better fit are getMatrixColumnLength
and getMatrixRowLength
.
Redundant Method Names
Each method name expect dotProduct
contains some how the word matrix.
It is sufficient if the methods are grouped in a Matrix
module and have names like:
// in matrix.js
export const columnLenghtOf = (a: number[][]) =>
a[0].length;
export const rowLengthOf = (a: number[][]) =>
a.length;
export const areValid = (a: number[][], b: number[][]) =>
columnLenghtOf(a) === columnLenghtOf(b);
/* ... */
Type Alias
Matrix
could be a type alias for number[][]
:
// in matrix.js
type Matrix = number[][]
export const columnLenghtOf = (a: Matrix) =>
a[0].length;
```