Skip to content

Commit e0883fa

Browse files
committed
Refactor Maths/Factorial for more minimal side effects.
1 parent 90891b5 commit e0883fa

File tree

2 files changed

+10
-25
lines changed

2 files changed

+10
-25
lines changed

Maths/Factorial.js

Lines changed: 10 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,36 +14,24 @@
1414
'use strict'
1515

1616
const calcRange = (num) => {
17-
// Generate a range of numbers from 1 to `num`.
18-
let i = 1
19-
const range = []
20-
while (i <= num) {
21-
range.push(i)
22-
i += 1
23-
}
24-
return range
17+
return [...Array(num).keys()].map(i => i + 1);
2518
}
2619

2720
const calcFactorial = (num) => {
28-
let factorial
29-
const range = calcRange(num)
3021

31-
// Check if the number is negative, positive, null, undefined, or zero
32-
if (num < 0) {
33-
return 'Sorry, factorial does not exist for negative numbers.'
34-
}
35-
if (num === null || num === undefined) {
36-
return 'Sorry, factorial does not exist for null or undefined numbers.'
22+
if (num > 0) {
23+
const range = calcRange(num)
24+
const factorial = range.reduce((a, c) => a * c, 1);
25+
return `The factorial of ${num} is ${factorial}`
3726
}
3827
if (num === 0) {
3928
return 'The factorial of 0 is 1.'
4029
}
41-
if (num > 0) {
42-
factorial = 1
43-
range.forEach(function (i) {
44-
factorial = factorial * i
45-
})
46-
return `The factorial of ${num} is ${factorial}`
30+
if (num < 0) {
31+
return 'Sorry, factorial does not exist for negative numbers.'
32+
}
33+
if (!num) {
34+
return 'Sorry, factorial does not exist for null or undefined numbers.'
4735
}
4836
}
4937

Maths/test/Factorial.test.js

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
import { calcFactorial } from '../Factorial'
22

33
describe('calcFactorial', () => {
4-
it('is a function', () => {
5-
expect(typeof calcFactorial).toEqual('function')
6-
})
74

85
it('should return a statement for value "0"', () => {
96
expect(calcFactorial(0)).toBe('The factorial of 0 is 1.')

0 commit comments

Comments
 (0)