HardPro challengePythonJavaScriptTypeScript

Trampoline

FunctionsRecursionPatterns

JavaScript lacks native tail-call optimization. The trampoline pattern
solves this: instead of calling itself recursively, a function returns a
thunk (a zero-argument function). The trampoline runner calls it
repeatedly until it gets a non-function result.

Implement trampoline(fn) — a higher-order function that wraps fn and
keeps calling it as long as the result is a function.

Then implement solve(n) which computes the n-th triangular number
(1+2+…+n) using a trampolined recursive function.

Sample tests

Test #11+2+3+4+5 = 15
Input: [5]
Output: 15
Test #2n=1 → 1
Input: [1]
Output: 1
Test #3n=0 → 0
Input: [0]
Output: 0
Test #41+2+…+10 = 55
Input: [10]
Output: 55
Test #51+2+…+100 = 5050 (Gauss)
Input: [100]
Output: 5050