Here is a naive implementation of a right fold:
const foldr = f => acc => ([x, ...xs]) =>
x === undefined
? acc
: f(x) (foldkr(f) (acc) (xs));
Run Code Online (Sandbox Code Playgroud)
This is non-tail recursion and hence we cannot apply a trampoline. One approach would be to make the algorithm iterative and use a stack to mimick the function call stack.
Another approch would be to transform the recursion into CPS:
const Cont = k => ({runCont: k});
const foldkr = f …Run Code Online (Sandbox Code Playgroud) javascript continuations functional-programming trampolines continuation-passing