mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
chore: check for invalid input to factorial (#1229)
This commit is contained in:

committed by
GitHub

parent
d9d085faa7
commit
5364a1c31b
@ -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
|
||||
}
|
||||
|
@ -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')
|
||||
})
|
||||
})
|
||||
|
Reference in New Issue
Block a user