Singledispatch

Benchmark created on


Setup

// Create a generic function that dispatches on the first argument.
// Returns a wrapped function that calls `defun`.
//
// Custom implementations for specific types can be registered through calling
// `.register(constructor, fun)` on the returned function.
//
// The default implementation is also exposed at `.default`.
const dispatching = defun => {
  let key = Symbol(`singledispatch`)

  const singledispatch = (subject, ...rest) => {
    let fun = subject[key]
    if (fun) {
      return fun(subject, ...rest)
    }
    return defun(subject, ...rest)
  }

  const register = (constructor, fun) => {
    constructor.prototype[key] = fun
  }

  singledispatch.register = register

  singledispatch.default = defun

  return singledispatch
}

class Test {
	x = 10

	log() {
		return this.x * this.x
	}
}

let log = dispatching(thing => console.log(thing))

log.register(Test, test => test.x * test.x)

let test = new Test()

Test runner

Ready to run.

Testing in
TestOps/sec
Method dispatch
test.log()
ready
Single dispatch
log(test)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.