Created
November 2, 2019 20:24
-
-
Save ChillyBwoy/7ff0cb39c60c4b8cb390cce8bd78e62f to your computer and use it in GitHub Desktop.
Multimethod
This file contains hidden or 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
function multiMethod() { | |
const methodMap = new Map(); | |
const fn = function (name, ...args) { | |
const fn = methodMap.get(name); | |
if (typeof fn === 'undefined') { | |
throw new TypeError(`Invalid method name "${name}"`); | |
} | |
return fn(...args); | |
}; | |
fn.def = function (name, fn) { | |
if (methodMap.has(name)) { | |
throw new TypeError(`Method "${name}" is already defined`); | |
} | |
methodMap.set(name, fn); | |
return this; | |
}; | |
return fn; | |
} | |
const calulcator = multiMethod() | |
.def('+', (a, b) => a + b) | |
.def('-', (a, b) => a - b) | |
.def('*', (a, b) => a * b) | |
.def('/', (a, b) => a / b); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment