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

throw-error-for-negative-factorial #1011

Closed
wants to merge 2 commits into from
Closed
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
5 changes: 5 additions & 0 deletions src/algorithms/math/factorial/__test__/factorial.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@ import factorial from '../factorial';
describe('factorial', () => {
it('should calculate factorial', () => {
expect(factorial(0)).toBe(1);
expect(factorial(-0)).toBe(1);
expect(factorial(1)).toBe(1);
expect(factorial(5)).toBe(120);
expect(factorial(8)).toBe(40320);
expect(factorial(10)).toBe(3628800);
});
it('should throw exception', () => {
expect(() => factorial(-1)).toThrowError('Factorial of a negative number (-1) does not exist!');
expect(() => factorial(-10)).toThrowError('Factorial of a negative number (-10) does not exist!');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@ import factorialRecursive from '../factorialRecursive';
describe('factorialRecursive', () => {
it('should calculate factorial', () => {
expect(factorialRecursive(0)).toBe(1);
expect(factorialRecursive(-0)).toBe(1);
expect(factorialRecursive(1)).toBe(1);
expect(factorialRecursive(5)).toBe(120);
expect(factorialRecursive(8)).toBe(40320);
expect(factorialRecursive(10)).toBe(3628800);
});
it('should throw exception', () => {
expect(() => factorialRecursive(-1)).toThrowError('Factorial of a negative number (-1) does not exist!');
expect(() => factorialRecursive(-10)).toThrowError('Factorial of a negative number (-10) does not exist!');
});
});
1 change: 1 addition & 0 deletions src/algorithms/math/factorial/factorial.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* @return {number}
*/
export default function factorial(number) {
if (number < 0) throw new Error(`Factorial of a negative number (${number}) does not exist!`);
let result = 1;

for (let i = 2; i <= number; i += 1) {
Expand Down
1 change: 1 addition & 0 deletions src/algorithms/math/factorial/factorialRecursive.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
* @return {number}
*/
export default function factorialRecursive(number) {
if (number < 0) throw new Error(`Factorial of a negative number (${number}) does not exist!`);
return number > 1 ? number * factorialRecursive(number - 1) : 1;
}