Skip to content

Commit f4023d8

Browse files
committed
fix(math): add input validation for negative numbers in factorial
The factorial function silently returned 1 for any negative input, which is mathematically incorrect since factorial is undefined for negative integers. Added a guard clause that throws a descriptive error when a negative number is passed. Added test cases to verify the error is thrown for negative inputs.
1 parent 3b53377 commit f4023d8

2 files changed

Lines changed: 17 additions & 0 deletions

File tree

src/algorithms/math/factorial/__test__/factorial.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,16 @@ describe('factorial', () => {
88
expect(factorial(8)).toBe(40320);
99
expect(factorial(10)).toBe(3628800);
1010
});
11+
12+
it('should throw an error for negative numbers', () => {
13+
const negativeFactorial = () => {
14+
factorial(-1);
15+
};
16+
expect(negativeFactorial).toThrow('Factorial is not defined for negative numbers');
17+
18+
const negativeFactorial2 = () => {
19+
factorial(-5);
20+
};
21+
expect(negativeFactorial2).toThrow('Factorial is not defined for negative numbers');
22+
});
1123
});

src/algorithms/math/factorial/factorial.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,11 @@
33
* @return {number}
44
*/
55
export default function factorial(number) {
6+
// Factorial is not defined for negative numbers.
7+
if (number < 0) {
8+
throw new Error('Factorial is not defined for negative numbers');
9+
}
10+
611
let result = 1;
712

813
for (let i = 2; i <= number; i += 1) {

0 commit comments

Comments
 (0)