Home Manual Reference Source Test

Enums for JS

Runtime Release License Downloads Dependencies Coverage Build

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:

const {Enum} = require('@cedx/enum');

/**
 * Specifies the day of the week.
 * @type {object}
 */
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 an Error: 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); // true
DayOfWeek.isDefined('Foo'); // false

Get the name associated to an enumerated value:

DayOfWeek.getName(DayOfWeek.TUESDAY); // "TUESDAY"
DayOfWeek.getName('Bar'); // "" (empty)

Get information about the enumerated type:

DayOfWeek.getNames();
// ["SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"]

DayOfWeek.getValues();
// [0, 1, 2, 3, 4, 5, 6]

See also

License

Enums for JS is distributed under the Apache License, version 2.0.