Skip to content

Commit

Permalink
feat(maths): add Factorial (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
skyfrk authored Oct 8, 2022
1 parent 9220f7c commit e298f3a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Maths/Factorial.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* @function Factorial
* @description Calculate the factorial of a natural number.
* @param {number} num - A natural number.
* @return {number} - The factorial.
* @see https://en.wikipedia.org/wiki/Factorial
* @example Factorial(0) = 1
* @example Factorial(3) = 6
*/
export const Factorial = (num: number): number => {
if (num < 0 || !Number.isInteger(num)) {
throw new Error("only natural numbers are supported");
}

return num === 0 ? 1 : num * Factorial(num - 1);
};
23 changes: 23 additions & 0 deletions Maths/test/Factorial.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Factorial } from "../Factorial";

describe("Factorial", () => {
test.each([-0.1, -1, -2, -42, 0.01, 0.42, 0.5, 1.337])(
"should throw an error for non natural number %d",
(num) => {
expect(() => Factorial(num)).toThrowError(
"only natural numbers are supported",
);
},
);

test.each([[1, 1], [3, 6], [5, 120], [10, 3628800]])(
"of %i should be %i",
(num, expected) => {
expect(Factorial(num)).toBe(expected);
},
);

test("of 1 should be 0 by definition", () => {
expect(Factorial(0)).toBe(1);
});
});

0 comments on commit e298f3a

Please sign in to comment.