Skip to content

Instantly share code, notes, and snippets.

@xgrommx
Forked from andyhd/pattern-matching.js
Created January 11, 2014 01:06
Show Gist options
  • Save xgrommx/8365635 to your computer and use it in GitHub Desktop.
Save xgrommx/8365635 to your computer and use it in GitHub Desktop.
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