Skip to content

Instantly share code, notes, and snippets.

@svanellewee
Last active August 29, 2015 14:04
Show Gist options
  • Save svanellewee/31a8a48143d76488c020 to your computer and use it in GitHub Desktop.
Save svanellewee/31a8a48143d76488c020 to your computer and use it in GitHub Desktop.
Trampolining
// with recursion:
var results = [1,1];
function recufib(N) {
function getN() {
var a = results[results.length-2]
var b = results[results.length-1];
if(!--N) {
return;
} else {
results.push(a+b);
getN();
}
};
//return getN;
getN();
}
recufib(30);
console.log(results) // cool
// using a trampoline!
var results=[1,1];
function fib(N) {
function getN() {
var a = results[results.length-2]
var b = results[results.length-1];
if(!--N) {
return;
} else {
results.push(a+b);
return getN;
}
};
return getN;
}
b = fib(30);
while (b instanceof Function) {
b = b(); // trampolining?
}
console.log(results)
/*
~/source/nodejs$ node tramp.js
[ 1,
1,
2,
3,
5,
8,
13,
21,
34,
55,
89,
144,
233,
377,
610,
987,
1597,
2584,
4181,
6765,
10946,
17711,
28657,
46368,
75025,
121393,
196418,
317811,
514229,
832040,
1346269 ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment