Skip to content

Commit 273a165

Browse files
committed
feat(factorial): Add factorial module
1 parent cc2b919 commit 273a165

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { trampoline, identity } from '../utils';
2+
3+
const factorial = n => {
4+
if (n <= 1) return 1;
5+
return n * factorial(n - 1);
6+
};
7+
8+
const factorialPTC = (n, totalSoFar = 1) => {
9+
if (n <= 1) return totalSoFar;
10+
const newTotalSoFar = n * totalSoFar;
11+
return factorialPTC(n - 1, newTotalSoFar);
12+
};
13+
14+
const factorialCPS = (n, cont = identity) => {
15+
if (n <= 1) return cont(1);
16+
return factorialCPS(n - 1, remainingResult => cont(remainingResult * n));
17+
};
18+
19+
const factorialTrampoline = trampoline(function _factorialTrampoline(
20+
n,
21+
totalSoFar = 1,
22+
) {
23+
if (n <= 1) return totalSoFar;
24+
return () => _factorialTrampoline(n - 1, n * totalSoFar);
25+
});
26+
27+
export { factorial, factorialPTC, factorialCPS, factorialTrampoline };
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import each from 'jest-each';
2+
import {
3+
factorial,
4+
factorialPTC,
5+
factorialCPS,
6+
factorialTrampoline,
7+
} from './factorial';
8+
9+
[factorial, factorialPTC, factorialCPS, factorialTrampoline].forEach(fn => {
10+
describe(`${fn.name}`, () => {
11+
each`
12+
n | expected
13+
${0} | ${1}
14+
${1} | ${1}
15+
${2} | ${2}
16+
${3} | ${6}
17+
${4} | ${24}
18+
${5} | ${120}
19+
`.test('should return $expected when called with $n', ({ n, expected }) => {
20+
expect(fn(n)).toBe(expected);
21+
});
22+
});
23+
});

0 commit comments

Comments
 (0)