Skip to content

Commit e298f3a

Browse files
authored
feat(maths): add Factorial (#38)
1 parent 9220f7c commit e298f3a

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

Maths/Factorial.ts

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* @function Factorial
3+
* @description Calculate the factorial of a natural number.
4+
* @param {number} num - A natural number.
5+
* @return {number} - The factorial.
6+
* @see https://en.wikipedia.org/wiki/Factorial
7+
* @example Factorial(0) = 1
8+
* @example Factorial(3) = 6
9+
*/
10+
export const Factorial = (num: number): number => {
11+
if (num < 0 || !Number.isInteger(num)) {
12+
throw new Error("only natural numbers are supported");
13+
}
14+
15+
return num === 0 ? 1 : num * Factorial(num - 1);
16+
};

Maths/test/Factorial.test.ts

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { Factorial } from "../Factorial";
2+
3+
describe("Factorial", () => {
4+
test.each([-0.1, -1, -2, -42, 0.01, 0.42, 0.5, 1.337])(
5+
"should throw an error for non natural number %d",
6+
(num) => {
7+
expect(() => Factorial(num)).toThrowError(
8+
"only natural numbers are supported",
9+
);
10+
},
11+
);
12+
13+
test.each([[1, 1], [3, 6], [5, 120], [10, 3628800]])(
14+
"of %i should be %i",
15+
(num, expected) => {
16+
expect(Factorial(num)).toBe(expected);
17+
},
18+
);
19+
20+
test("of 1 should be 0 by definition", () => {
21+
expect(Factorial(0)).toBe(1);
22+
});
23+
});

0 commit comments

Comments
 (0)