Extensible type definitions
This library provides simple but very extensible way to define types / classes / constructors in JS. It comes a very small set of functions to do that, but any function can be incorporated to allow more complex definitions.
It's quite common to have constructors that just set given arguments as properties of the instance, providing rest of the API through prototype methods. This library makes this task simple by reducing all the machinery code:
var Point = definerecord 'x' 'y'
Code above will produce constructor which is equivalent of:
var Point =thisx = xthsy = y
Commonly you will want to define some methods for the
Point type, that
can be done as follows:
var Point = definerecord 'x' 'y'implementthisx = 0thisy = 0
You could also extend existing types in similar way:
var Pixel = definerecord 'x' 'y' 'color'extend Pointimplement// ...
record is limited to a very specific scenarios, but more generic use
cases are also covered:
var Dog = defineconstructthisname = optionsname// ...extend Animalimplement// ....
You could also refine existing types in a same way:
defineover EventEmitterimplementvar times = 0thisontype listenerthisontypeif ++ times === 2thisremoveListenertype listenerthisremoveListenertype limiter
While this tiny library provides some core functionailty for building and
extending types / constructors / classes, there is no way it could cover all
use cases. That's not an issues since all the functionality is defined in
via simple functions like
record... You could
incorporate your own functions to do more sophisticated things. For example
adding aspect oriented programming
concepts is very easy:
var prototype = typeprototypeObjectkeysmethodsforEachvar before = prototypenamevar after = methodsnameprototypename =beforeapplythis argumentsreturn aftercallthisreturn typevar Point3D = definerecord 'x' 'y' 'z'extend Pointafterthisz = 0// EventEmitter2defineover EventEmitterafterif type !== '*'thisemitapplythis '*'concatArrayprototypeslicecallarguments
You could in fact do so much more! Enforce API contracts using guards, define extensions on built-ins types without changing their prototypes via [type based dispatch] (https://github.com/Gozala/protocol) or do a [pattern based dispatch] (https://github.com/Gozala/dispatcher/) or maybe something entirely new!
npm install alter-ego