ramda-adjunct icon indicating copy to clipboard operation
ramda-adjunct copied to clipboard

trampoline

Open char0n opened this issue 6 years ago • 0 comments

Is your feature request related to a problem? Please describe.

All that trampoline does is repeatedly call the return value of a function until it’s no longer a function

Describe the solution you'd like

function evenOline(n) {
  if (n === 0)
    return true;
  else
    return partial1(oddOline, Math.abs(n) - 1);
}

function oddOline(n) {
  if (n === 0)
    return false;
  else
    return partial1(evenOline, Math.abs(n) - 1);
}

trampoline(oddOline, 3);
//=> true
trampoline(evenOline, 200000);
//=> true

trampoline(oddOline, 300000);
//=> false

trampoline(evenOline, 200000000);
// wait a few seconds
//=> true

Describe alternatives you've considered

Additional context

The code and exmplanation comes from book Functional Javascript by Michael Fogus. Possible implementation for the function:

function trampoline(fun /*, args */) {
  var result = fun.apply(fun, _.rest(arguments));

  while (_.isFunction(result)) {
    result = result();
  }

  return result;
}

char0n avatar Dec 24 '19 13:12 char0n