Williammer
4/10/2016 - 2:11 AM

## recursion

recursion

``````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);
}``````
``````// ES6
const _sum = accu => ([first, ...rest]) =>
first === undefined ? accu : _sum(first + accu)(rest)

const sum = (...vals) => _sum(0)(vals)``````
``````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");``````
``````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.");``````
``````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;
}``````
``//test``