Skip to content

Instantly share code, notes, and snippets.

@Williammer
Last active June 5, 2016 11:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Williammer/b7fa74368b2c889b246d629f25af3a90 to your computer and use it in GitHub Desktop.
Save Williammer/b7fa74368b2c889b246d629f25af3a90 to your computer and use it in GitHub Desktop.
recursion
function trampoline(func /*, args */ ) {
var rest = Array.prototype.slice.call(arguments, 1),
result = func.apply(func, rest);
while (typeof result === "function") {
result = result();
}
return result;
}
// ES6 rewrite
// NOTE: this seems to have issue when the func is partialled
const trampoline = (func, ...vals) => {
let result = func.apply(func, vals);
while (typeof result === "function") {
result = result();
}
return result;
}
var ninja = {
chirp: function signal(n) {
return n > 1 ? signal(n - 1) + "-chirp" : "chirp";
}
};
assert(ninja.chirp(3) == "chirp-chirp-chirp",
"Works as we would expect it to!");
var samurai = {
chirp: ninja.chirp
};
ninja = {};
assert(samurai.chirp(3) == "chirp-chirp-chirp",
"The method correctly calls itself.");
var hanoi = function (discNum, src, aux, dst) {
if (discNum > 0) { // 1. make the last one of disc be seen.
hanoi(discNum - 1, src, dst, aux); // move all disc to Aux until last one is seen.
console.log("move disc [" + discNum + "] from " + src + " to " + dst);
hanoi(discNum - 1, aux, src, dst); // move the last one of src to dst
}
};
hanoi(3, "src-panel", "aux-middle", "dst-panel");
// ES6
const _sum = accu => ([first, ...rest]) =>
first === undefined ? accu : _sum(first + accu)(rest)
const sum = (...vals) => _sum(0)(vals)
function factorial(n) {
function fact(n,res) {
if (n < 2) return res;
return fact( n - 1, n * res );
}
return fact( n, 1 );
}
factorial( 5 ); // 120
// original factorial
function factorial(n) {
if (n < 2) return 1;
return n * factorial(n-1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment