-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_factorial.js
More file actions
59 lines (45 loc) · 1.24 KB
/
01_factorial.js
File metadata and controls
59 lines (45 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
Implement the below function to calculate the factorial of `number`.
Examples:
factorial(3) => 6
factorial(0) => 1
factorial(5) => 120
*Your function must return a value*
It's not necessary to print the result on screen,
however to test your function you are free to print the result
*/
function decreasingByOne(number) {
return number - 1;
}
function getProductOf(num1, num2) {
return num1 * num2;
}
function factorial(number) {
let fact = 1;
let factorialCandidate = number;
while (factorialCandidate > 1) {
fact = getProductOf(fact, factorialCandidate);
factorialCandidate = decreasingByOne(factorialCandidate);
}
return fact;
}
function getMark(isPassed) {
return isPassed ? '✅' : '❌';
}
function makeMessage(number, actual, expected) {
const message = "Factorial of '" + number + "' should be '" + expected;
return message + "' giving " + actual;
}
function testFactorial(number, expected) {
const actual = factorial(number);
const isPassed = actual === expected;
console.log(getMark(isPassed), makeMessage(number, actual, expected));
}
function testAll() {
testFactorial(0, 1);
testFactorial(1, 1);
testFactorial(2, 2);
testFactorial(3, 6);
testFactorial(4, 24);
}
testAll();