singledispatch

Benchmark created on


Description

An implementation of Python-style single dispatch on first argument.

Setup

const error = type => {
  throw new TypeError(`singledispatch not implemented for type ${type.constructor.name}`)
}

// 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 wrapped function.
//
// The default implementation is also exposed at `.default` on the wrapped
// function.
const singledispatch = (defun=error) => {
  let key = Symbol('singledispatch')

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

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

  return dispatch
}

let total = singledispatch()

class Group {
	constructor(lions, tigers, bears) {
		this.lions = lions
		this.tigers = tigers
		this.bears = bears
	}

	total() {
		return this.lions + this.tigers + this.bears
	}
}

total.register(Group, group => group.total())

let group = new Group(10, 3, 50)

Test runner

Ready to run.

Testing in
TestOps/sec
singledispatch
total(group)
ready
method
group.total()
ready

Revisions

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