Created
March 6, 2018 19:13
-
-
Save jameskeane/8198fbb4e7bd095db36fc295e8172b80 to your computer and use it in GitHub Desktop.
Stack unwinder
This file contains 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
function tco(f) { | |
let isin = false; | |
return function() { | |
if (isin) throw [this, arguments]; | |
isin = true; | |
let args = [this, arguments]; | |
while(true) { | |
try { | |
const ret = f.apply(args[0], args[1]); | |
isIn = false; | |
return ret; | |
} catch(e) { | |
args = e; | |
} | |
} | |
} | |
}; | |
// example | |
function sum(s) { | |
const sub = tco((i, acc) => { | |
if (i >= s.length) return acc; | |
return sub(i + 1, acc + s[i]); | |
}); | |
return sub(0, 0); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment