javascriptrecursiontrampolines

How to understand trampoline in JavaScript?


Here is the code:

function repeat(operation, num) {
  return function() {
    if (num <= 0) return
    operation()
    return repeat(operation, --num)
  }
}

function trampoline(fn) {
  while(fn && typeof fn === 'function') {
    fn = fn()
  }
}

module.exports = function(operation, num) {
  trampoline(function() {
    return repeat(operation, num)
  })
}

I have read that the trampoline is used to deal with overflow problems, so the function would not just keep calling itself and cause the stack to fill up.

But how does this snippet function? Especially the trampoline function? What did it exactly do by while and how did it accomplish its goal?


Solution

  • The while loop will keep running until the condition is falsy.

    fn && typeof fn === 'function' will be falsy either if fn itself is falsy, or if fn is anything other than a function.

    The first half is actually redundant, since falsy values are also not functions.