Enumerate
An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way withing your code.
Enumerate is JS Pseudo-Enums inspired by Swift.
While we aren't very concerned with type-safety in JS it is sometimes still useful to have a small convention around defining a common type for a group of related values.
Enumerate provides this convention.
Version
v0.0.1
Dependencies
- Underscore or Lodash ~latest
Available Files
- Development Version of enumerate.js
- Production Version of enumerate.js
- Bundled Production Version of enumerate.js
The bundled version comes with Underscore 1.8.3 bundled in.
Installation
Html
// main.js{ // ... }window Enumerate;
RequireJS
// standard define; // or// commonJS style importsvar Enumerate = ;
Node
var Enumerate = ;
Usage
Check out the specs for more usage examples!
Check out src/enumerate.js for docs / comments!
There are essentially two ways to construct an Enumerate.Enum type:
- As an associative enum
- As an enum with a raw value
Associative Value Enum Example
Sometimes it's useful to store associated values alongside enum values. This enables the storage of additional custom information and permits this information to vary each time.
var ProductCode = "Barcode" "QrCode" "ISBN"; var { thisproductCode = productCode;} var toy = ProductCode ; console; // => 85909-51226
Raw Value Enums
Sometimes you just need a simple data structure to store some basic values for a small set of read-only object keys. This is where raw value enums come in handy.
Raw value enums can store any valid JS type.
Raw value enums should share the same data type by convention.
var direction = North: "north" South: "south" East: "east" West: "west"; var dir = directionNorth; // => To Canada!
Feeling Iterable?
// iterate over enum as a list of EnumValues _; // iterate over enum as a list of keys _; // iterate over enum as a list of {key, EnumValue} pairs _;
Custom Types
Enumerate.EnumValue and Enumerate.Enum are extendable via a familiar .extend
method.
var DirectionEnumValue = EnumerateEnumValue; var DirectionEnum = EnumerateEnum; var direction = north: "north" south: "south" east: "east" west: "west"; console;// => [DirectionEnumValue] north | [DirectionEnumValue] south | [DirectionEnumValue] east | [DirectionEnumValue] west