Skip to content

Instantly share code, notes, and snippets.

@ewebdev
Created April 15, 2018 12:17
Show Gist options
  • Save ewebdev/257e98e70aafaa5d3682207d9bb2f13e to your computer and use it in GitHub Desktop.
Save ewebdev/257e98e70aafaa5d3682207d9bb2f13e to your computer and use it in GitHub Desktop.
Overloading Javascript Functions
const overload = (() => {
const noop = () => {};
const typeOf = (p) => (Object.prototype.toString.call(p).slice(8,-1));
return (fns) => (function (...args) {
const key = args.map(typeOf).join('_');
return (fns[key] || noop).apply(this, args);
});
})();
// USAGE EXAMPLE
let greet = overload({
String: (name) => `Hi, ${name}!`,
Array: (names) => `Hello ${names.join(', ')}!`,
Number: (x) => `Welcome number ${x} :)`,
Array_Function: (arr, f) => arr.map(f)
});
console.log(greet('Tom'))
//=> "Hello Tom"
greet(['Alice', 'Bob', 'Carol']);
//=> "Hello Alice, Bob, Carol!"
greet(6);
//=> "Welcome number 6 :)"
greet(['Dave', 'Eve', 'Frank'], (name) => `${name} is here!`);
//=> ["Dave is here!", "Eve is here!", "Frank is here!"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment