polymorf
Version:
Polymorphic function dispatch
74 lines (53 loc) • 1.87 kB
Markdown
Create a polymorphic function that dispatches to different handler functions based on the type of the parameters it is passed.
```js
var add = polymorf(
[],
function (a, b) {
return a + b
},
[],
function (a, b) {
// Don't concat
return parseFloat(a) + parseFloat(b)
}
)
add(2, 3) // 5
add('10', '12') // 22
```
Create a new polymorphic function. Arguments are `signature, handler` pairs, where `signature` is an array of **types** and `handler` is the function to be called if the polymorphic function is called with arguments whose types match the signature.
The following types are permitted as values in the signature array.
* Object
* Function
* String
* Error
* Number
* Array
* Boolean
* RegExp
* Date
* null
* undefined
You can also pass your own custom types. Internally polymorf will check if values match the type in the signature using the `instanceof` operator.
Use the `polymorf.Any` type matcher to match **any** value.
Given a polymorphic function `fn`, a new handler for a signature can be dynamically added. e.g.
```js
var doubler = polymorf()
try {
doubler(4) // Throws
} catch (er) {
console.error('No signatures to match against')
}
doubler.polymorf.add([Number], function (x) {
return x * 2
})
doubler(4) // 8
```
Given a polymorphic function `fn`, an existing handler for a signature can be dynamically removed.