-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStacklessRecursion.js
More file actions
46 lines (33 loc) · 1.13 KB
/
StacklessRecursion.js
File metadata and controls
46 lines (33 loc) · 1.13 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
function stacklessRecursion(func) {
return function(...args) {
let stack = [func(...args)];
let ret = undefined;
while (stack.length > 0) {
let iterationResult = stack[stack.length - 1].next(ret);
if (iterationResult.done) {
ret = iterationResult.value;
stack.pop();
} else {
stack.push(func(...iterationResult.value))
}
}
return ret;
};
}
function stacklessRecursion_UsageExample() {
const factorial = stacklessRecursion(function*(i) {
return i <= 1 ? 1 : i * (yield [i - 1]);
});
const fibonacci = stacklessRecursion(function*(i) {
return i <= 1 ? i : (yield [i - 1]) + (yield [i - 2]);
})
console.log("Factorial:");
for (let t = 0; t < 100; ++t)
console.log(factorial(t));
console.log(factorial(100000));
console.log("Completed successfully without a crash!");
console.log("\nFibonacci:");
for (let t = 0; t < 25; ++t)
console.log(fibonacci(t));
}
stacklessRecursion_UsageExample();