fix: factorial function (#1093)

This commit is contained in:
Akshay Dubey
2022-09-07 15:00:35 +05:30
committed by GitHub
parent 6f55ed4a1f
commit 61c9e8b372
2 changed files with 11 additions and 21 deletions

View File

@ -19,18 +19,18 @@ const calcRange = (num) => {
const calcFactorial = (num) => { const calcFactorial = (num) => {
if (num === 0) { if (num === 0) {
return 'The factorial of 0 is 1.' return 1
} }
if (num < 0) { if (num < 0) {
return 'Sorry, factorial does not exist for negative numbers.' throw Error('Sorry, factorial does not exist for negative numbers.')
} }
if (!num) { if (!num) {
return 'Sorry, factorial does not exist for null or undefined numbers.' throw Error('Sorry, factorial does not exist for null or undefined numbers.')
} }
if (num > 0) { if (num > 0) {
const range = calcRange(num) const range = calcRange(num)
const factorial = range.reduce((a, c) => a * c, 1) const factorial = range.reduce((a, c) => a * c, 1)
return `The factorial of ${num} is ${factorial}` return factorial
} }
} }

View File

@ -2,30 +2,20 @@ import { calcFactorial } from '../Factorial'
describe('calcFactorial', () => { describe('calcFactorial', () => {
it('should return a statement for value "0"', () => { it('should return a statement for value "0"', () => {
expect(calcFactorial(0)).toBe('The factorial of 0 is 1.') expect(calcFactorial(0)).toBe(1)
}) })
it('should return a statement for "null" and "undefined"', () => { it('should throw error for "null" and "undefined"', () => {
const nullFactorial = calcFactorial(null) expect(() => { calcFactorial(null) }).toThrow(Error)
const undefinedFactorial = calcFactorial(undefined) expect(() => { calcFactorial(undefined) }).toThrow(Error)
expect(nullFactorial).toBe(
'Sorry, factorial does not exist for null or undefined numbers.'
)
expect(undefinedFactorial).toBe(
'Sorry, factorial does not exist for null or undefined numbers.'
)
}) })
it('should not support negative numbers', () => { it('should throw error for negative numbers', () => {
const negativeFactorial = calcFactorial(-5) expect(() => { calcFactorial(-1) }).toThrow(Error)
expect(negativeFactorial).toBe(
'Sorry, factorial does not exist for negative numbers.'
)
}) })
it('should return the factorial of a positive number', () => { it('should return the factorial of a positive number', () => {
const positiveFactorial = calcFactorial(3) const positiveFactorial = calcFactorial(3)
expect(positiveFactorial).toBe('The factorial of 3 is 6') expect(positiveFactorial).toBe(6)
}) })
}) })