JavaScriptFundamental (ES6), part 1
Trampoline to avoid stack overflow in JavaScript
129 a trampoline for recursion too deep for the stack
hardShow that a tail-recursive sum blows the stack at two hundred thousand, then convert it: instead of calling itself, each step returns a description of the next call, and a small loop keeps bouncing until it gets a result. Do the same for a pair of mutually recursive functions, which no amount of rewriting into a single loop would fix as neatly.
Stuck? Three hints, smallest first
- 1. Two makers is all the vocabulary you need:
more(fn, ...args)anddone(value), both plain objects. - 2. The trampoline is a
whileloop: as long as it holds amore, call it and keep what comes back. - 3. The recursive function no longer recurses —
return more(self, n - 1, acc + n)ends the frame before the next step begins.
const more = (fn, ...args) => ({ tag: 'more', fn, args });
const done = (value) => ({ tag: 'done', value });
const trampoline = (start) => {
let step = start;
while (step.tag === 'more') step = step.fn(...step.args);
return step.value;
};
const sumTo = (n, acc = 0) => (n === 0 ? acc : sumTo(n - 1, acc + n));
let blewUp = 'no error';
try { sumTo(200000); } catch (e) { blewUp = e.constructor.name; }
const sumStep = (n, acc = 0) => (n === 0 ? done(acc) : more(sumStep, n - 1, acc + n));
const bounced = trampoline(sumStep(200000));
let plain = 0;
for (let i = 1; i <= 200000; i++) plain += i;
let bounces = 0;
const counted = (n, acc = 0) => {
bounces += 1;
return n === 0 ? done(acc) : more(counted, n - 1, acc + n);
};
const smallSum = trampoline(counted(5));
const isEven = (n) => (n === 0 ? done(true) : more(isOdd, n - 1));
const isOdd = (n) => (n === 0 ? done(false) : more(isEven, n - 1));
const parity = [trampoline(isEven(100001)), trampoline(isEven(4))];
const firstStep = sumStep(3);
console.log('direct :', blewUp);
console.log('trampoline:', bounced, '| plain loop:', plain);
console.log('parity :', parity, '| bounces for 5:', bounces);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('two hundred thousand frames is more than the stack holds', blewUp, 'RangeError');
test('the trampoline gets the answer anyway', bounced, 20000100000);
test('and it agrees with the loop nobody needed a trick for', bounced === plain, true);
test('the small case is ordinary arithmetic', smallSum, 15);
test('one bounce per step, plus the one that returns done', bounces, 6);
test('mutual recursion trampolines just as well', parity, [false, true]);
test('a done value passes straight through with no bouncing', trampoline(done(9)), 9);
test('shallow recursion still works directly, so this is a choice not a rule', sumTo(1000) === trampoline(sumStep(1000)), true);
test('and each step is a plain object you could log or queue', { tag: firstStep.tag, args: firstStep.args, fn: typeof firstStep.fn }, { tag: 'more', args: [2, 3], fn: 'function' });
JavaScript engines do not eliminate tail calls — the specification asks for it, and no major engine implements it — so a tail-recursive function is exactly as stack-hungry as any other. The stack is somewhere around ten thousand frames deep, which is plenty until you meet a long list, a deep tree, or a state machine that steps once per input character.
The trampoline swaps the stack for a loop. Each step returns before the next begins, so the depth is always one, and the "recursion" lives in the while. The price is a small object per step and a function that no longer reads like the algorithm — which is why the eighth assertion is there: for a thousand items, plain recursion is clearer and works fine.
Where it genuinely earns its place is mutual recursion, and anything where the next step is chosen at run time. isEven and isOdd calling each other cannot be turned into one obvious loop, but as trampolined steps they need no rewriting at all. The same shape underlies interpreters and schedulers: a step is data — { tag, fn, args } — so you can log it, count it, pause between bounces, or hand it to a queue.