multimethods (v5)

Revision 5 of this benchmark created on


Description

Clojure-style multimethod

Setup

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

  const func = (...rest) => {
    let key = dispatch(...rest)
    let method = methods.get(key)
    return method(...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(
  (a, b) => `${a.type}-${b.type}`
)

add.define(
  'v2d-v2d',
  (a, b) => v2d(
    a.x + b.x,
  	a.y + b.y
  )
)

const v2d = (x, y) => ({type: 'v2d', x, y})

let origin = v2d(0, 0)

let originCoords = new Coords(0, 0)
let offsetCoords = v2d(5, -5)

Test runner

Ready to run.

Testing in
TestOps/sec
multimethod
add(origin, offsetCoords)
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.