Skip to content

Commit cc2b919

Browse files
committed
refactor(utils): Extract trampoline and identity utility functions
1 parent 46f4160 commit cc2b919

File tree

4 files changed

+18
-20
lines changed

4 files changed

+18
-20
lines changed

src/recursion-practice/power/power.js

+2-11
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { trampoline, identity } from '../utils';
2+
13
// Power
24
const power = (base, exponent) => {
35
if (exponent === 0) {
@@ -16,7 +18,6 @@ const powerPTC = (base, exponent, resultSoFar = 1) => {
1618
};
1719

1820
// Power continuous passing style
19-
const identity = x => x;
2021
const powerCPS = (base, exponent, cont = identity) => {
2122
if (exponent === 0) {
2223
return cont(1);
@@ -25,16 +26,6 @@ const powerCPS = (base, exponent, cont = identity) => {
2526
};
2627

2728
// Power with trampolining
28-
const trampoline = fn => (...args) => {
29-
let result = fn(...args);
30-
31-
while (typeof result === 'function') {
32-
result = result();
33-
}
34-
35-
return result;
36-
};
37-
3829
const powerTrampoline = trampoline(function _power(
3930
base,
4031
exponent,

src/recursion-practice/sumRange/sumRange.js

+2-9
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { trampoline, identity } from '../utils';
2+
13
// sumRange with no optimisations
24
const sumRange = n => {
35
if (n <= 1) return n;
@@ -29,7 +31,6 @@ const sumRangePTCFacade = (() => {
2931
})();
3032

3133
// sumRange with continuous passing style
32-
const identity = x => x;
3334
const sumRangeCPS = (n, cont = identity) => {
3435
if (n <= 1) return cont(n);
3536

@@ -38,14 +39,6 @@ const sumRangeCPS = (n, cont = identity) => {
3839
};
3940

4041
// sumRange with trampolining
41-
const trampoline = fn => (...args) => {
42-
let result = fn(...args);
43-
while (typeof result === 'function') {
44-
result = result();
45-
}
46-
return result;
47-
};
48-
4942
const sumRangeTrampoline = trampoline(function _sumRange(n, totalSoFar = 0) {
5043
const newTotalSoFar = n + totalSoFar;
5144

src/recursion-practice/utils/index.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './utils';

src/recursion-practice/utils/utils.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const trampoline = fn => (...args) => {
2+
let result = fn(...args);
3+
4+
while (typeof result === 'function') {
5+
result = result();
6+
}
7+
8+
return result;
9+
};
10+
11+
const identity = x => x;
12+
13+
export { trampoline, identity };

0 commit comments

Comments
 (0)