Skip to content

Instantly share code, notes, and snippets.

@ralphtheninja
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralphtheninja/8736091 to your computer and use it in GitHub Desktop.
Save ralphtheninja/8736091 to your computer and use it in GitHub Desktop.
overloading functions in javascript (from DailyJS)
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