Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Last active November 18, 2022 05:05
Show Gist options
  • Select an option

  • Save gordonbrander/1793395e2d638d65fde8 to your computer and use it in GitHub Desktop.

Select an option

Save gordonbrander/1793395e2d638d65fde8 to your computer and use it in GitHub Desktop.
Javascript multimethods
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'
// 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