Protocol JS library is inspired by idea of clojure protocols. Protocols provide a powerful way for decoupling abstraction interface definition from an actual implementation per type, without risks of interference with other libraries.
There are several motivations for protocols:
A protocol is a named set of function signatures:
var protocol = require'protocol/core'protocolvar Sequential = protocolfirst: 'Returns first item of this sequence' protocolrest: 'Returns sequence of items after the first' protocoljoin: 'Returns sequence of items where head is first, and this is rest' Object protocol
protocolargument, and thus must have it in the list of arguments.
protocol will generate an interface containing a corresponding functions.
returned interface may be used to extend data types with it's implementations:
SequentialArrayreturn array0 || nullreturn Arrayprototypeslicecallarray 1return Arrayprototypeconcatcall item array
Once protocol is implemented for a given type it can be used with a given data types:
Sequentialfirst 1 2 3 // => 1Sequentialrest 1 2 3 // => [ 2, 3 ]Sequentialfirst'hello' // TypeError: Protocol not implemented: first
Protocol may be implemented for any other data types by any other party:
SequentialStringreturn string0 || nullreturn Stringprototypesubstrcallstring 1return item + stringSequentialfirst'hello' // => 'h'
Protocol implementation may be provided to all the data types by ommiting type argument:
Sequentialreturn _return nullSequentialhead5 // => 5Sequentialtail3 // => null
Since protocol implementations are decoupled from the actual protocol definition there maybe multiple implementations, but user will be in charge of deciding which one to pull in.
This library previously was doing argument pattern based method dispatch. If you are looking into something more in that line, check out dispatcher library that was forked from protocol to explore that direction.