Created
January 24, 2020 15:07
-
-
Save aykutyaman/426fed48e5811be657cb5a9f99d11bff to your computer and use it in GitHub Desktop.
proper tail call with trampoline in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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