throw-error-for-negative-factorial

This commit is contained in:
Devesh35 2023-04-02 20:20:57 +05:30
parent bbbfd32a45
commit 85d17f8f64
4 changed files with 12 additions and 0 deletions

View File

@ -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!');
});
});

View File

@ -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!');
});
});

View File

@ -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) {

View File

@ -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;
}