multimethods

Benchmark created on


Description

Clojure-style multimethod

Setup

const multimethod = dispatch => {
  const methods = new Map()

  const func = (object, ...rest) => {
    let key = dispatch(object, ...rest)
    let method = methods.get(key)
    return method(object, ...rest)
  }

  func.define = (key, method) => {
    methods.set(key, method)
  }

  return func
}

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

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

const add = multimethod(x => x.type)

add.define(
  'vec2d',
  (object, x, y) => ({
  	type: 'vec2d',
  	x: object.x + x,
  	y: object.y + y
  })
)

let origin = {
	type: 'vec2d',
	x: 0,
	y: 0
}

let originCoords = new Coords(0, 0)

Test runner

Ready to run.

Testing in
TestOps/sec
multimethod
add(origin, 5, -5)
ready
vanilla method
originCoords.add(5, -5)
ready

Revisions

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