-
-
Save xgrommx/8365635 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function when(x) { | |
return function () { | |
for (var i in arguments) { | |
var result = arguments[i](x); | |
if (result !== false) { | |
return result; | |
} | |
} | |
throw "No patterns matched when(" + x + ")"; | |
}; | |
} | |
function match(pattern) { | |
return function (then) { | |
return function (x) { | |
var match = pattern === "*" ? true : pattern(x); | |
return match !== false ? then(match) : false; | |
} | |
} | |
} | |
function isZero(n) { return n === 0; } | |
function nonZero(n) { var i = parseInt(n); return i > 0 ? i : false; } | |
var fact = function (n) { | |
return when(n)( | |
match(isZero)(function () { return 1; }), | |
match(nonZero)(function (n) { return n * fact(n - 1); }) | |
); | |
} | |
console.log(fact(10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment