Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(maths): add Factorial #38

Merged
merged 5 commits into from
Oct 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
skyfrk marked this conversation as resolved.
Show resolved Hide resolved
};
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);
});
});