From f4023d8ae51b938ea83c3f34c5f7f5271d0fdc9a Mon Sep 17 00:00:00 2001 From: fauzan171 Date: Sun, 7 Jun 2026 00:09:08 +0700 Subject: [PATCH] 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. --- .../math/factorial/__test__/factorial.test.js | 12 ++++++++++++ src/algorithms/math/factorial/factorial.js | 5 +++++ 2 files changed, 17 insertions(+) diff --git a/src/algorithms/math/factorial/__test__/factorial.test.js b/src/algorithms/math/factorial/__test__/factorial.test.js index bf6aa0ecbd..369d7f73ef 100644 --- a/src/algorithms/math/factorial/__test__/factorial.test.js +++ b/src/algorithms/math/factorial/__test__/factorial.test.js @@ -8,4 +8,16 @@ describe('factorial', () => { expect(factorial(8)).toBe(40320); expect(factorial(10)).toBe(3628800); }); + + it('should throw an error for negative numbers', () => { + const negativeFactorial = () => { + factorial(-1); + }; + expect(negativeFactorial).toThrow('Factorial is not defined for negative numbers'); + + const negativeFactorial2 = () => { + factorial(-5); + }; + expect(negativeFactorial2).toThrow('Factorial is not defined for negative numbers'); + }); }); diff --git a/src/algorithms/math/factorial/factorial.js b/src/algorithms/math/factorial/factorial.js index 6c717d051f..425fcf75bf 100644 --- a/src/algorithms/math/factorial/factorial.js +++ b/src/algorithms/math/factorial/factorial.js @@ -3,6 +3,11 @@ * @return {number} */ export default function factorial(number) { + // Factorial is not defined for negative numbers. + if (number < 0) { + throw new Error('Factorial is not defined for negative numbers'); + } + let result = 1; for (let i = 2; i <= number; i += 1) {