Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Created March 23, 2013 00:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/5225698 to your computer and use it in GitHub Desktop.
Save gordonbrander/5225698 to your computer and use it in GitHub Desktop.
JavaScript multiple dispatch using predicate functions
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