Skip to content

Commit 4097bb8

Browse files
committed
feat: error handling for non-integer values
A TypeError will now be thrown when a non-integer number is used in the dimensions parameter
1 parent 88e2045 commit 4097bb8

File tree

4 files changed

+17
-3
lines changed

4 files changed

+17
-3
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ const threeDimensionalStringArray = makeMatrix([2, 6, 5], "value");
7272

7373
### Pass a callback for dynamic initial values
7474

75-
The `initialValues` parameter also accepts a callback which you can use to dynamically create items for each position in the matrix.
75+
The `initialValues` parameter also accepts a callback, which you can use to dynamically create items for each position in the matrix.
7676

7777
```js
7878
// create a 10x10x10 array, with each point a different random number between one and 10
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import makeMatrix from "../index";
22

33
// Test arrays of specific dimensions, with callbacks returning initialised values
4-
test("length: 1 test - With string initialValues", () => {
4+
test("length: 1 test - With string callback initialValues", () => {
55
expect(makeMatrix([1], () => "string")).toStrictEqual(["string"]);
66
});
77

8-
test("length: 2 test - With string initialValues", () => {
8+
test("length: 2 test - With math callback initialValues", () => {
99
expect(makeMatrix([2], () => 10 - 2)).toStrictEqual([8, 8]);
1010
});
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import makeMatrix from "../index";
2+
3+
// Test the throwing of a TypeError if a non-integer is passed in `dimensions`
4+
test("Array error test - When non-integer is used", () => {
5+
expect(() => makeMatrix([1, 0.2, 3])).toThrow(TypeError);
6+
});
7+
8+
test("Number error test - When non-integer is used", () => {
9+
expect(() => makeMatrix(0.2)).toThrow(TypeError);
10+
});

src/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,10 @@ function makeMatrix<T>(
7979
needsRecursion = remainingDimensions.length > 0;
8080
}
8181

82+
if (!Number.isInteger(currentDimensionLength)) {
83+
throw new TypeError(`Dimensions must be integers`);
84+
}
85+
8286
// Spread operator used as as constructed array's can't be mapped:
8387
// https://itnext.io/heres-why-mapping-a-constructed-array-doesn-t-work-in-javascript-f1195138615a
8488
const currentMatrix = [...Array(currentDimensionLength)].map(() => {

0 commit comments

Comments
 (0)