Skip to content

Commit 61c9e8b

Browse files
fix: factorial function (TheAlgorithms#1093)
1 parent 6f55ed4 commit 61c9e8b

File tree

2 files changed

+11
-21
lines changed

2 files changed

+11
-21
lines changed

Maths/Factorial.js

+4-4
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,18 @@ const calcRange = (num) => {
1919

2020
const calcFactorial = (num) => {
2121
if (num === 0) {
22-
return 'The factorial of 0 is 1.'
22+
return 1
2323
}
2424
if (num < 0) {
25-
return 'Sorry, factorial does not exist for negative numbers.'
25+
throw Error('Sorry, factorial does not exist for negative numbers.')
2626
}
2727
if (!num) {
28-
return 'Sorry, factorial does not exist for null or undefined numbers.'
28+
throw Error('Sorry, factorial does not exist for null or undefined numbers.')
2929
}
3030
if (num > 0) {
3131
const range = calcRange(num)
3232
const factorial = range.reduce((a, c) => a * c, 1)
33-
return `The factorial of ${num} is ${factorial}`
33+
return factorial
3434
}
3535
}
3636

Maths/test/Factorial.test.js

+7-17
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,20 @@ import { calcFactorial } from '../Factorial'
22

33
describe('calcFactorial', () => {
44
it('should return a statement for value "0"', () => {
5-
expect(calcFactorial(0)).toBe('The factorial of 0 is 1.')
5+
expect(calcFactorial(0)).toBe(1)
66
})
77

8-
it('should return a statement for "null" and "undefined"', () => {
9-
const nullFactorial = calcFactorial(null)
10-
const undefinedFactorial = calcFactorial(undefined)
11-
12-
expect(nullFactorial).toBe(
13-
'Sorry, factorial does not exist for null or undefined numbers.'
14-
)
15-
expect(undefinedFactorial).toBe(
16-
'Sorry, factorial does not exist for null or undefined numbers.'
17-
)
8+
it('should throw error for "null" and "undefined"', () => {
9+
expect(() => { calcFactorial(null) }).toThrow(Error)
10+
expect(() => { calcFactorial(undefined) }).toThrow(Error)
1811
})
1912

20-
it('should not support negative numbers', () => {
21-
const negativeFactorial = calcFactorial(-5)
22-
expect(negativeFactorial).toBe(
23-
'Sorry, factorial does not exist for negative numbers.'
24-
)
13+
it('should throw error for negative numbers', () => {
14+
expect(() => { calcFactorial(-1) }).toThrow(Error)
2515
})
2616

2717
it('should return the factorial of a positive number', () => {
2818
const positiveFactorial = calcFactorial(3)
29-
expect(positiveFactorial).toBe('The factorial of 3 is 6')
19+
expect(positiveFactorial).toBe(6)
3020
})
3121
})

0 commit comments

Comments
 (0)