AniUI Academy
hard+350 XPPractice

Trampoline a deep recursion

JavaScript has no guaranteed tail-call optimisation, so a recursion a hundred thousand deep throws a stack overflow. A trampoline sidesteps this: the recursive function, instead of calling itself, returns a zero-argument function — a thunk — describing the next step, and a driver loop keeps calling thunks until a real value comes back. The stack never grows past one frame.

Implement trampoline(fn). It returns a wrapper that calls fn with all of the arguments it was given, then, as long as the result is a function, calls that result with no arguments, repeating until the result is not a function, and returns that final value. If fn returns a non-function straight away, the wrapper returns it as-is. Because each bounce is a fresh call from the loop rather than a nested call, a recursion of any depth is safe, and thunks may point at a different function each bounce, which makes mutual recursion work too.

What it has to do

  • Call fn with every argument the wrapper received.
  • Keep invoking the returned thunk, with no arguments, while the result is a function.
  • Return the first non-function result, including when fn returns one immediately.
  • Survive a recursion deep enough to overflow the call stack.
  • Work when the thunks alternate between two mutually recursive functions.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.