Skip to content

Commit

Permalink
fix: Enhance error handling in factorial function (#1430)
Browse files Browse the repository at this point in the history
  • Loading branch information
yongeazi143 authored Oct 5, 2023
1 parent 1de5ab7 commit 96d122f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
9 changes: 3 additions & 6 deletions Recursive/Factorial.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,14 @@
*/

const factorial = (n) => {
if (!Number.isInteger(n)) {
throw new RangeError('Not a Whole Number')
}

if (n < 0) {
throw new RangeError('Not a Positive Number')
if (!Number.isInteger(n) || n < 0) {
throw new RangeError('Input should be a non-negative whole number')
}

if (n === 0) {
return 1
}

return n * factorial(n - 1)
}

Expand Down
20 changes: 15 additions & 5 deletions Recursive/test/Factorial.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,20 @@ describe('Factorial', () => {
})

it('Throw Error for Invalid Input', () => {
expect(() => factorial('-')).toThrow('Not a Whole Number')
expect(() => factorial(null)).toThrow('Not a Whole Number')
expect(() => factorial(undefined)).toThrow('Not a Whole Number')
expect(() => factorial(3.142)).toThrow('Not a Whole Number')
expect(() => factorial(-1)).toThrow('Not a Positive Number')
expect(() => factorial('-')).toThrow(
'Input should be a non-negative whole number'
)
expect(() => factorial(null)).toThrow(
'Input should be a non-negative whole number'
)
expect(() => factorial(undefined)).toThrow(
'Input should be a non-negative whole number'
)
expect(() => factorial(3.142)).toThrow(
'Input should be a non-negative whole number'
)
expect(() => factorial(-1)).toThrow(
'Input should be a non-negative whole number'
)
})
})

0 comments on commit 96d122f

Please sign in to comment.