Skip to content

Commit 96d122f

Browse files
authored
fix: Enhance error handling in factorial function (TheAlgorithms#1430)
1 parent 1de5ab7 commit 96d122f

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

Recursive/Factorial.js

+3-6
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,14 @@
99
*/
1010

1111
const factorial = (n) => {
12-
if (!Number.isInteger(n)) {
13-
throw new RangeError('Not a Whole Number')
14-
}
15-
16-
if (n < 0) {
17-
throw new RangeError('Not a Positive Number')
12+
if (!Number.isInteger(n) || n < 0) {
13+
throw new RangeError('Input should be a non-negative whole number')
1814
}
1915

2016
if (n === 0) {
2117
return 1
2218
}
19+
2320
return n * factorial(n - 1)
2421
}
2522

Recursive/test/Factorial.test.js

+15-5
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,20 @@ describe('Factorial', () => {
1010
})
1111

1212
it('Throw Error for Invalid Input', () => {
13-
expect(() => factorial('-')).toThrow('Not a Whole Number')
14-
expect(() => factorial(null)).toThrow('Not a Whole Number')
15-
expect(() => factorial(undefined)).toThrow('Not a Whole Number')
16-
expect(() => factorial(3.142)).toThrow('Not a Whole Number')
17-
expect(() => factorial(-1)).toThrow('Not a Positive Number')
13+
expect(() => factorial('-')).toThrow(
14+
'Input should be a non-negative whole number'
15+
)
16+
expect(() => factorial(null)).toThrow(
17+
'Input should be a non-negative whole number'
18+
)
19+
expect(() => factorial(undefined)).toThrow(
20+
'Input should be a non-negative whole number'
21+
)
22+
expect(() => factorial(3.142)).toThrow(
23+
'Input should be a non-negative whole number'
24+
)
25+
expect(() => factorial(-1)).toThrow(
26+
'Input should be a non-negative whole number'
27+
)
1828
})
1929
})

0 commit comments

Comments
 (0)