Enums for JS
Yet another implementation of enumerated types for JavaScript.
This implementation does not try to reproduce the semantics of traditional enumerations, like the ones found in C# or Java languages. It just gives a set of static methods to ease working with the values of an object literal representing an enumerated type.
Requirements
The latest Node.js and npm versions.
If you plan to play with the sources, you will also need the latest Gulp.js version.
Installing via npm
From a command prompt, run:
$ npm install --save @cedx/enum
Usage
Create the enumeration
Just use the Enum.create()
method with an object literal containing scalar values:
import {Enum} from '@cedx/enum';
const DayOfWeek = Enum.create({
SUNDAY: 0,
MONDAY: 1,
TUESDAY: 2,
WEDNESDAY: 3,
THURSDAY: 4,
FRIDAY: 5,
SATURDAY: 6
});
The Enum.create()
method creates an anonymous class from the specified object. This class has the same values as the provided object, and some additional helper methods.
The created class has a constructor throwing a TypeError
: it prohibits its instantiation. This class is also freezed to prevent any attempt at modifying its shape.
Work with the enumeration
Check whether a value is defined among the enumerated type:
DayOfWeek.isDefined(DayOfWeek.TUESDAY);
DayOfWeek.isDefined('Foo');
Get the name associated to an enumerated value:
DayOfWeek.getName(DayOfWeek.TUESDAY);
DayOfWeek.getName('Bar');
Get information about the enumerated type:
DayOfWeek.getNames();
DayOfWeek.getValues();
See also
License
Enums for JS is distributed under the Apache License, version 2.0.