Skip to content

chore: check for invalid input to factorial #1229

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Oct 27, 2022
12 changes: 12 additions & 0 deletions Recursive/Factorial.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@
*/

const factorial = (n) => {
if (typeof n !== 'number') {
throw new TypeError('Not a Number')
}

if ((n % 1) !== 0) {
throw new RangeError('Not a Whole Number')
}

if (n < 0) {
return new RangeError('Not a Positive Number')
}

if (n === 0) {
return 1
}
Expand Down
8 changes: 8 additions & 0 deletions Recursive/test/Factorial.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 Number')
expect(() => factorial(null)).toThrow('Not a Number')
expect(() => factorial(undefined)).toThrow('Not a Number')
expect(() => factorial(3.142)).toThrow('Not a Whole Number')
expect(() => factorial(-1)).toThrow('Not a Positive Number')
})
})