Skip to content

Instantly share code, notes, and snippets.

@aykutyaman
Created January 24, 2020 15:07
Show Gist options
  • Save aykutyaman/426fed48e5811be657cb5a9f99d11bff to your computer and use it in GitHub Desktop.
Save aykutyaman/426fed48e5811be657cb5a9f99d11bff to your computer and use it in GitHub Desktop.
proper tail call with trampoline in javascript
var trampoline = fn => (n) => {
// make sure we call trampoline function only once
var result = fn(n);
while (typeof result === 'function') {
result = result();
}
return result;
}
// The recursive function should be a proper tail call, and return recursive call wrapped with a function
var counter = c => {
if (c === 200000) return; // base case
if (c % 5000 === 0) console.log(c);
return () => counter(c + 1);
}
var counterT = trampoline(counter);
counterT(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment