Skip to content

Instantly share code, notes, and snippets.

@elclanrs
Last active January 3, 2016 20:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elclanrs/8515458 to your computer and use it in GitHub Desktop.
Save elclanrs/8515458 to your computer and use it in GitHub Desktop.
var __slice = [].slice;
var __noop = function(){};
function typeOf(x) {
return {}.toString.call(x).slice(8,-1);
}
function overload(fs) {
return function() {
var types = __slice.call(arguments).map(typeOf);
var f = fs[types.join('_')] || __noop;
return f.apply(this, arguments);
};
}
var fn = overload({
String: function greet(s) {
return 'Hello '+ s;
},
Number: function square(x) {
return x * x;
},
Array_Function: function map(xs, f) {
return xs.map(f);
},
RegExp_String_Number: function replace(re, s, x) {
return s.replace(re, x);
}
});
fn('Joe'); //=> "Hello Joe"
fn(3); //=> 9
fn([1,2,3], function(x){ return x+1 }); //=> [2,3,4]
fn(/a/g, 'wawa', 2); //=> "w2w2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment