Last active
March 29, 2017 14:47
-
-
Save ChillyBwoy/3617c0313bb3bcdd3923 to your computer and use it in GitHub Desktop.
Multimethod in js
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
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