Created
April 15, 2018 12:17
-
-
Save ewebdev/257e98e70aafaa5d3682207d9bb2f13e to your computer and use it in GitHub Desktop.
Overloading Javascript Functions
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
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