Prototype-friendly multiple method dispatch for JS.


genfun.js is hosted at Github. genfun.js is a public domain work, dedicated using CC0 1.0. Feel free to do whatever you want with it.


genfun.js is available through both NPM and Bower as genfun.

$ npm install genfun or $ bower install genfun

The npm version includes a build/ directory with both pre-built and minified UMD versions of genfun.js which are loadable by both AMD and CommonJS module systems. UMD will define window.Genfun if neither AMD or CommonJS are used. To generate these files in bower, or if you fetched genfun.js from source, simply run:

$ npm install dependencies installed...
$ make

And use build/genfun.js or build/genfun.min.js in your application.

Various examples are availble to look at in the examples/ folder included in this project. Most examples are also runnable with node, or by just doing make example-<name> (for example, make example-fmap).

// Based on examples/hellodog.js 
var Genfun = require("genfun"),
    addMethod = Genfun.addMethod;
function Person() {}
function Dog() {}
// Creates a generic function. This is a regular, callable function. 
var frobnicate = new Genfun();
// addMethod is used to define new methods on genfuns, with the most 
// "specific"  method firing when multiple methods are applicable to a set of 
// arguments when the genfun is called. 
// addMethod(<genfun>, <selector>, <method function>) 
addMethod(frobnicate, [Person.prototype], function(person) {
  console.log("Got a person!");
addMethod(frobnicate, [Dog.prototype], function(dog) {
  console.log("Got a dog!");
// Selectors can include multiple arguments, which correspond to argument 
// positions when the genfun is called. 
// This last method will dispatch only when a string, a Person, and a Dog 
// are the arguments to frobnicate (in that order). 
  [String.prototype, Person.prototype, Dog.prototype],
  function(greetingpersondog) {
    console.log(person, " greets ", dog, ", '"+greeting+"'");
var person = new Person(),
    dog = new Dog();
frobnicate(person); // Got a person! 
frobnicate(dog); // Got a dog! 
frobnicate("Hi, dog!", person, dog); // {} greets {}, 'Hi, dog!' 


genfun.js is a library that provides multimethod/generic function capabilities in a prototype-friendly way. Inspired by Slate, CLOS and Sheeple. In this case, 'prototype-friendly' means that it doesn't keep references from methods to objects, so they will be garbage collected normally even if a method has been directly defined on them.