Skip to content

Commit 9513bcd

Browse files
authored
merge: WhileLoopFactorial: Optimize and add tests (TheAlgorithms#992)
* Optimised the factorial function. There was previously an unnecessary check for if the number was 0 or 1. * Create WhileLoopFactorial.test.js The test was not present previously. * result *= num * Update WhileLoopFactorial.test.js * testFactorial function * Space for formatting. * should fix the formatting issues. I was having trouble with npx standard, so I just used the online verifier at https://standardjs.com/demo.html
1 parent 1e0dd1c commit 9513bcd

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

Maths/WhileLoopFactorial.js

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
/*
2-
author: Theepag
2+
author: Theepag, optimised by merelymyself
33
*/
44
export const factorialize = (num) => {
5-
// Step 1. variable result to store num
6-
let result = num
7-
// If num = 0 OR 1, the factorial will return 1
8-
if (num === 0 || num === 1) { return 1 }
5+
// Step 1. Handles cases where num is 0 or 1, by returning 1.
6+
let result = 1
97
// Step 2. WHILE loop
108
while (num > 1) {
9+
result *= num // or result = result * num;
1110
num-- // decrement 1 at each iteration
12-
result = result * num // or result = result * num;
1311
}
1412
// Step 3. Return the factorial
1513
return result

Maths/test/WhileLoopFactorial.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { factorialize } from '../WhileLoopFactorial'
2+
3+
function testFactorial (n, expected) {
4+
test('Testing on ' + n + '!', () => {
5+
expect(factorialize(n)).toBe(expected)
6+
})
7+
}
8+
9+
testFactorial(3, 6)
10+
testFactorial(7, 5040)
11+
testFactorial(0, 1)
12+
testFactorial(12, 479001600)

0 commit comments

Comments
 (0)