chore: check for invalid input to factorial (#1229)

This commit is contained in:
Abdulrazak Yahuza
2022-10-27 19:45:53 +01:00
committed by GitHub
parent d9d085faa7
commit 5364a1c31b
2 changed files with 16 additions and 0 deletions

View File

@ -9,6 +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 (n === 0) {
return 1
}

View File

@ -8,4 +8,12 @@ describe('Factorial', () => {
it('should return factorial 120 for value "5"', () => {
expect(factorial(5)).toBe(120)
})
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')
})
})