Last active
August 29, 2015 13:55
-
-
Save ralphtheninja/8736091 to your computer and use it in GitHub Desktop.
overloading functions in javascript (from DailyJS)
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 __toString = {}.toString | |
var __noop = function (){} | |
function typeOf(x) { | |
return __toString.call(x).slice(8,-1) | |
} | |
function overload(fs) { | |
return function () { | |
var type = __slice.call(arguments).map(typeOf).join('_') | |
var f = fs[type] || __noop | |
return f.apply(this, arguments) | |
} | |
} | |
var fn = overload({ | |
String: function (s) { | |
return 'Hello '+ s | |
}, | |
Number: function (x) { | |
return x * x | |
}, | |
Array_Function: function (xs, f) { | |
return xs.map(f) | |
}, | |
RegExp_String_Number: function (re, s, x) { | |
return s.replace(re, x) | |
} | |
}) | |
console.log(fn('Joe')) | |
//=> "Hello Joe" | |
console.log(fn(3)) | |
//=> 9 | |
console.log(fn([1,2,3], function(x){ return x+1 })) | |
//=> [2,3,4] | |
console.log(fn(/a/g, 'wawa', 2)) | |
//=> "w2w2" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment