Skip to content

Instantly share code, notes, and snippets.

@rads
Created February 24, 2010 07:47
Show Gist options
  • Save rads/313225 to your computer and use it in GitHub Desktop.
Save rads/313225 to your computer and use it in GitHub Desktop.
window.onload = function() {
window.multi = function(dispatchFn) {
var methods = [];
var fn = function() {
var val = dispatchFn.apply(this, arguments);
return (typeof methods[val] !== "undefined" ? methods[val] : methods['default'])();
}
fn.method = function(dispatchVal, tailFn) {
methods[dispatchVal] = tailFn;
}
return fn;
}
var foo = multi(function(x) { return [x.rank, x.lvl]; });
foo.method(['silver', 'one'], function() { return "silver one"; });
foo.method(['silver', 'two'], function() { return "silver two"; });
foo.method(['gold', 'one'], function() { return "gold one"; });
foo.method(['gold', 'two'], function() { return "gold two"; })
foo.method('default', function() { return "default"; });
alert(foo({ rank: 'silver', lvl: 'one' }));
alert(foo({ rank: 'silver', lvl: 'two' }));
alert(foo({ rank: 'gold', lvl: 'one' }));
alert(foo({ rank: 'gold', lvl: 'two' }));
alert(foo({ rank: 'platinum', lvl: 'one' }));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment