JavaScript Functional Pattern Matching
Adrien Friggeri has been playing with pattern matching in JavaScript a la functional programming.
Take a look at the examples such as writing a factorial via matching:
JAVASCRIPT:
function fact (n) {
return m.match(n,
[
[ 0 , function ( ) { return 1 }],
[ _("n"), function (a) { return (a.n * fact(a.n -1)) }]
]);
}
return m.match(n,
[
[ 0 , function ( ) { return 1 }],
[ _("n"), function (a) { return (a.n * fact(a.n -1)) }]
]);
}
or working with complex structures:
JAVASCRIPT:
function go_deep(ob) {
return m.match(ob,
[
[{foo:{bar:{baz:'foo'}}, baz:_('b')}, function (a) { return a.b }],
[_('_') , function ( ) { return null }]
]);
}
return m.match(ob,
[
[{foo:{bar:{baz:'foo'}}, baz:_('b')}, function (a) { return a.b }],
[_('_') , function ( ) { return null }]
]);
}
When is this useful? Adrien is "sure some genius out there would find a cool use for it : dom navigation ? input validation ? json validation ? you name it :)"
Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/241458625/javascript-functional-pattern-matching