Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Last active October 19, 2023 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/72721085332be31289790e7faa86f882 to your computer and use it in GitHub Desktop.
Save gordonbrander/72721085332be31289790e7faa86f882 to your computer and use it in GitHub Desktop.
singledispatch.js - single dispatch generic function like Python's singledispatch
// Create a Python singledispatch / Clojure multimethod style function that
// dispatches on the first argument.
//
// Returns a wrapped function that calls appropriate underlying function
// based on prototype of first argument.
//
// Custom implementations for specific types can be registered through calling
// `.define(constructor, fun)` on the wrapped function.
export const singledispatch = fallback => {
let _key = Symbol('singledispatch method')
// Assign fallback to Object prototype.
// This makes it the method of last resort.
Object.prototype[_key] = fallback
const dispatch = (object, ...rest) => {
let method = object[_key]
return method(object, ...rest)
}
dispatch.define = (constructor, method) => {
constructor.prototype[_key] = method
}
return dispatch
}
export default singledispatch
@gordonbrander
Copy link
Author

gordonbrander commented Mar 26, 2023

Surprisingly fast in Chrome and Safari... In the same ballpark as plain function call, or method dispatch https://jsperf.app/sanega

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment