fix: Enhance error handling in factorial function (#1430)

This commit is contained in:
YongEaziDev
2023-10-05 11:00:28 +01:00
committed by GitHub
parent 1de5ab7d71
commit 96d122f29e
2 changed files with 18 additions and 11 deletions

View File

@ -9,17 +9,14 @@
*/ */
const factorial = (n) => { const factorial = (n) => {
if (!Number.isInteger(n)) { if (!Number.isInteger(n) || n < 0) {
throw new RangeError('Not a Whole Number') throw new RangeError('Input should be a non-negative whole number')
}
if (n < 0) {
throw new RangeError('Not a Positive Number')
} }
if (n === 0) { if (n === 0) {
return 1 return 1
} }
return n * factorial(n - 1) return n * factorial(n - 1)
} }

View File

@ -10,10 +10,20 @@ describe('Factorial', () => {
}) })
it('Throw Error for Invalid Input', () => { it('Throw Error for Invalid Input', () => {
expect(() => factorial('-')).toThrow('Not a Whole Number') expect(() => factorial('-')).toThrow(
expect(() => factorial(null)).toThrow('Not a Whole Number') 'Input should be a non-negative whole number'
expect(() => factorial(undefined)).toThrow('Not a Whole Number') )
expect(() => factorial(3.142)).toThrow('Not a Whole Number') expect(() => factorial(null)).toThrow(
expect(() => factorial(-1)).toThrow('Not a Positive Number') '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'
)
}) })
}) })