Last active
October 19, 2023 13:57
-
-
Save gordonbrander/72721085332be31289790e7faa86f882 to your computer and use it in GitHub Desktop.
singledispatch.js - single dispatch generic function like Python's singledispatch
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
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Surprisingly fast in Chrome and Safari... In the same ballpark as plain function call, or method dispatch https://jsperf.app/sanega