diff --git a/src/algorithms/math/factorial/__test__/factorial.test.js b/src/algorithms/math/factorial/__test__/factorial.test.js index bf6aa0ecbd..8e923b1d88 100644 --- a/src/algorithms/math/factorial/__test__/factorial.test.js +++ b/src/algorithms/math/factorial/__test__/factorial.test.js @@ -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!'); + }); }); diff --git a/src/algorithms/math/factorial/__test__/factorialRecursive.test.js b/src/algorithms/math/factorial/__test__/factorialRecursive.test.js index 9029faee0a..99e43a05c1 100644 --- a/src/algorithms/math/factorial/__test__/factorialRecursive.test.js +++ b/src/algorithms/math/factorial/__test__/factorialRecursive.test.js @@ -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!'); + }); }); diff --git a/src/algorithms/math/factorial/factorial.js b/src/algorithms/math/factorial/factorial.js index 6c717d051f..611cfd8cc3 100644 --- a/src/algorithms/math/factorial/factorial.js +++ b/src/algorithms/math/factorial/factorial.js @@ -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) { diff --git a/src/algorithms/math/factorial/factorialRecursive.js b/src/algorithms/math/factorial/factorialRecursive.js index e2b4aec6c9..97d2b58e24 100644 --- a/src/algorithms/math/factorial/factorialRecursive.js +++ b/src/algorithms/math/factorial/factorialRecursive.js @@ -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; }