3
\$\begingroup\$

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);
 })
 );
 }
};
asked Feb 21, 2020 at 2:14
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

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;
```
answered Mar 6, 2020 at 17:34
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.