Created
March 23, 2013 00:06
-
-
Save gordonbrander/5225698 to your computer and use it in GitHub Desktop.
JavaScript multiple dispatch using predicate functions
This file contains 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
var nil = 'indicating a nil value'; | |
function reducePredicatePair(reduction, pair) { | |
// If no reduction has yet been found and the predicate | |
// matches, run the assocated function. | |
if(reduction[0] === nil && pair[0].apply(null, reduction[1])) { | |
reduction[0] = pair[1].apply(null, reduction[1]); | |
} | |
return reduction; | |
} | |
function dispatcher() { | |
// Predicate-function based multiple dispatch. | |
// function, [function, function]... -> function | |
// The first argument is a fallback function if no other function matches. | |
var fallback = arguments[0]; | |
// The rest arguments are pairs of predicate function + value function. | |
var pairs = Array.prototype.slice.call(arguments, 1); | |
return function composedDispatcher() { | |
var value = pairs.reduce(reducePredicatePair, [nil, arguments])[0]; | |
return value === nil ? fallback.apply(null, arguments) : value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment