Last active
January 3, 2016 20:29
-
-
Save elclanrs/8515458 to your computer and use it in GitHub Desktop.
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 __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