Skip to content

Instantly share code, notes, and snippets.

@ChillyBwoy
Last active March 29, 2017 14:47
Show Gist options
  • Save ChillyBwoy/3617c0313bb3bcdd3923 to your computer and use it in GitHub Desktop.
Save ChillyBwoy/3617c0313bb3bcdd3923 to your computer and use it in GitHub Desktop.
Multimethod in js
function multi(pred) {
const methods = new Map();
const fn = (...args) => {
const f = methods.get(pred(...args));
return f ? f(...args) : null;
};
fn.method = (predKey, methodFn) => {
methods.set(predKey, methodFn);
return fn;
};
return fn;
}
const hello = multi((data) => data.type)
.method('user', (data) => `Hello, ${data.name}`)
.method('guest', () => 'Hello, stranger');
console.log(hello({
type: 'user',
name: 'Andrey'
}));
console.log(hello({
type: 'guest'
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment