Skip to content

Instantly share code, notes, and snippets.

@bjouhier
Created March 9, 2012 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bjouhier/2008723 to your computer and use it in GitHub Desktop.
Save bjouhier/2008723 to your computer and use it in GitHub Desktop.
Simple code that breaks without trampoline
if (!require('streamline/module')(module)) return;
function fibo(_, n) {
return n > 1 ? fibo(_, n - 1) + fibo(_, n - 2) : 1;
}
function fibo2(_, n) {
return n > 1 ? trampo(this, 0, fibo2, _, n - 1) + trampo(this, 0, fibo2, _, n - 2) : 1;
}
function trampo(thisObj, index, fn) {
var state = 0,
err, result, args = Array.prototype.slice.call(arguments, 3), cb = args[index];
args[index] = function(e, r) {
if (state === 1) { // async
cb(e, r);
} else { // sync
state = 1;
err = e;
result = r;
}
};
fn.apply(thisObj, args);
if (state === 0) {
state = 1;
} else {
cb(err, result);
}
}
function fibo3(_, n) {
process.nextTick(_);
return n > 1 ? fibo3(_, n - 1) + fibo3(_, n - 2) : 1;
}
// console.log(fibo(_, 15)); // causes stack overflow
console.log(fibo2(_, 25)); // works!
console.log(fibo3(_, 25)); // works too!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment