Skip to content

Instantly share code, notes, and snippets.

@jameskeane
Created March 6, 2018 19:13
Show Gist options
  • Save jameskeane/8198fbb4e7bd095db36fc295e8172b80 to your computer and use it in GitHub Desktop.
Save jameskeane/8198fbb4e7bd095db36fc295e8172b80 to your computer and use it in GitHub Desktop.
Stack unwinder
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