singledispatch

Benchmark created on


Description

Python/Clojure style multimethod that dispatches on type of first argument.

Setup

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
}

class Coords {
	constructor(x, y) {
		this.x = x
		this.y = y
	}

	clone() {
		return new Coords(
			this.x,
			this.y
		)
	}

	add(x, y) {
		return new Coords(
			this.x + x,
			this.y + y
		)
	}
}

const clone = singledispatch()

clone.define(
  Coords,
  coords => new Coords(coords.x, coords.y)
)

const add = singledispatch()

add.define(
  Coords,
  (coords, x, y) => new Coords(
    coords.x + x,
    coords.y + y
  )
)

let origin = new Coords(0, 0)

Test runner

Ready to run.

Testing in
TestOps/sec
add singledispatch
add(origin, 5, -5)
ready
add method
origin.add(5, -5)
ready
clone singledispatch
clone(origin)
ready
clone method
origin.clone()
ready

Revisions

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