Skip to content

Commit

Permalink
fix: type check input array (#149)
Browse files Browse the repository at this point in the history
Check if every element in input array is numeric.

Fixes #148
  • Loading branch information
chrispahm authored May 31, 2022
1 parent 7a593b5 commit d8ac6f7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/__tests__/matrix/creation.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ describe('Matrix creation', () => {
expect(() => new Matrix()).toThrow(
/^First argument must be a positive number or an array$/,
);
expect(
() =>
new Matrix([
[1, 2, 3],
[4, 5, 6],
[7, undefined, 9],
]),
).toThrow(/^Input data contains non-numeric values$/);
});

it('should correctly set rows, columns and values', () => {
Expand Down
9 changes: 9 additions & 0 deletions src/matrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -1521,6 +1521,12 @@ function compareNumbers(a, b) {
return a - b;
}

function isArrayOfNumbers(array) {
return array.every((element) => {
return typeof element === 'number';
});
}

// Synonyms
AbstractMatrix.random = AbstractMatrix.rand;
AbstractMatrix.randomInt = AbstractMatrix.randInt;
Expand Down Expand Up @@ -1562,6 +1568,9 @@ export default class Matrix extends AbstractMatrix {
if (arrayData[i].length !== nColumns) {
throw new RangeError('Inconsistent array dimensions');
}
if (!isArrayOfNumbers(arrayData[i])) {
throw new TypeError('Input data contains non-numeric values');
}
this.data.push(Float64Array.from(arrayData[i]));
}
} else {
Expand Down

0 comments on commit d8ac6f7

Please sign in to comment.