def.js
A multiple-dispatch function overloading library for JavaScript.
Examples
Function overloading:
var def = ; var fibonacci = ; ; // 1; // 1; // 2; // 3
Simple router for node.js HTTP servers:
var http = def = handler = ; handler; handler; http;
Usage
Overloaded functions can be created using the def
function. It returns a dispatcher
function, which will later check the function arguments, and call the appropriate implementation
functions. Implementation functions are always associated with a function signature,
and can be defined with the def
method of the dispatcher. The first implementation and signature
may be defined when initally calling the standalone def
function.
The first parameters of the def
function are called the function signature or the filters.
Filters are described as JS schema. The first filter
applies to the first argument, the second applies to the second, etc. A typical function overloading
with signature definitions looks like this:
f = ;
Function call order
The most generic implementation must come first, then the special cases. It is explained by the way def.js executes the implementation functions. It goes like this:
- Select the last defined unchecked function implementation and signature
- Check the function signature against the function call's
arguments
and the value ofthis
- If the signature matches the
arguments
and the value ofthis
:
- Execute the implementation function with the given
arguments
andthis
- If the return value
ret
is notundefined
then stop executing and returnret
- Go to step 1 if there are unchecked implementations left
this
Filter for The filter for this
is also part of the function signature. To define a filter for the value
of this
, use def.call
or def.apply
.
print = def def; print; // Number: 1 (an important number)print; // String: a (the first letter)
Installation
Using npm:
npm install def.js
License
The MIT License
Copyright (C) 2012 Gábor Molnár gabor.molnar@sch.bme.hu