Skip to content

Instantly share code, notes, and snippets.

@ChillyBwoy
Created November 2, 2019 20:24
Show Gist options
  • Save ChillyBwoy/7ff0cb39c60c4b8cb390cce8bd78e62f to your computer and use it in GitHub Desktop.
Save ChillyBwoy/7ff0cb39c60c4b8cb390cce8bd78e62f to your computer and use it in GitHub Desktop.
Multimethod
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