-
-
Notifications
You must be signed in to change notification settings - Fork 362
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |