Skip to content

Commit 107a094

Browse files
author
patrickwestervelt
committed
Feat: IsEven and IsOdd
1 parent 12fa80b commit 107a094

File tree

4 files changed

+64
-0
lines changed

4 files changed

+64
-0
lines changed

Maths/IsEven.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* @function IsEven
3+
* @description Determine whether a number is even.
4+
* @param {Number} num - A number.
5+
* @return {Boolean} - Whether the given number is even.
6+
* @see https://en.wikipedia.org/wiki/Parity_(mathematics)
7+
* @example IsEven(1) = false
8+
* @example IsEven(2) = true
9+
*/
10+
export const IsEven = (num: number): boolean => {
11+
if (!Number.isInteger(num)) {
12+
throw new Error("only integers can be even or odd");
13+
}
14+
15+
return num % 2 === 0;
16+
};

Maths/IsOdd.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* @function IsOdd
3+
* @description Determine whether a number is odd.
4+
* @param {Number} num - A number.
5+
* @return {Boolean} - Whether the given number is odd.
6+
* @see https://en.wikipedia.org/wiki/Parity_(mathematics)
7+
* @example IsOdd(1) = true
8+
* @example IsOdd(2) = false
9+
*/
10+
export const IsOdd = (num: number): boolean => {
11+
if (!Number.isInteger(num)) {
12+
throw new Error("only integers can be even or odd");
13+
}
14+
15+
return num % 2 !== 0;
16+
};

Maths/test/IsEven.test.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { IsEven } from "../IsEven";
2+
3+
describe("IsEven", () => {
4+
test.each([[2, true], [1, false], [0, true], [-1, false], [-2, true]])(
5+
"correct output for for %i",
6+
(nums, expected) => {
7+
expect(IsEven(nums)).toBe(expected);
8+
},
9+
);
10+
11+
test("only whole numbers should be accepted", () => {
12+
expect(() => IsEven(0.5)).toThrowError(
13+
"only integers can be even or odd",
14+
);
15+
});
16+
});

Maths/test/IsOdd.test.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { IsOdd } from "../IsOdd";
2+
3+
describe("IsOdd", () => {
4+
test.each([[2, false], [1, true], [0, false], [-1, true], [-2, false]])(
5+
"correct output for for %i",
6+
(nums, expected) => {
7+
expect(IsOdd(nums)).toBe(expected);
8+
},
9+
);
10+
11+
test("only whole numbers should be accepted", () => {
12+
expect(() => IsOdd(0.5)).toThrowError(
13+
"only integers can be even or odd",
14+
);
15+
});
16+
});

0 commit comments

Comments
 (0)