Last active
November 18, 2022 05:05
-
-
Save gordonbrander/1793395e2d638d65fde8 to your computer and use it in GitHub Desktop.
Javascript multimethods
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
| import multimethod from './multimethod.js' | |
| const foo = multimethod(x => typeof x) | |
| foo.string = x => 'called string method' | |
| foo.number = x => 'called number method' | |
| foo('x') | |
| // 'called string method' | |
| foo(1) | |
| // 'called number method' |
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
| // Create a multiple dispatch function. | |
| // Methods can be registered by setting keys on function | |
| // that correspond to key generated by `dispatch`. | |
| // If no key is registered, will fall back to calling `multi._`, | |
| // which throws an error by default. | |
| // You can redefine `multi._` to set a default multimethod. | |
| export default const multimethod = dispatch => { | |
| const multi = (...args) => { | |
| const key = dispatch(...args) | |
| const method = multi[key] || multi._ | |
| return method(...args) | |
| } | |
| const _ = (...args) => { | |
| throw Error(`No multimethod defined for key "${dispatch(...args)}".`) | |
| } | |
| multi._ = _ | |
| return multi | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment