Enums
Functional enum implementation for JS based on @rbuckton's enum proposal.
Install
npm install --save fun-enums
Usage
const enums = ; // Default initializationconst weekdays = "monday" "tuesday" "wednesday" "thursday" "friday"; weekdaysmonday; // 0weekdaysfriday; // 4
Enums are frozen and should not be mutated after initializing. To avoid allowing mutation custom enum values should not be objects of depths greater than 1.
Initializers
fun-enums
is built around "initializers" which allow you to change the behavior of how the enum is created. The default initalizer is number
which sets the first enum value to 0 and increments each following by 1. fun-enums
also exposes a string
initializer which sets the value equal to the given enum name.
const enums string number = ;// Provide other initializers from the package like stringlet colors = 'red' 'green' 'blue'colorsred; // 'red' colors = 'red' 'green' 'blue'; // number does not need to be specified as it is the default behaviorcolorsred // 0
Custom initializers
You can also provide your own custom initializers by passing in an initialization function to enums
.
const enums = ; { return en + en;} const colors = 'red' 'green' 'blue';colorsred; // 'Red'
Your initializer will be passed these arguments:
arg | type | description |
---|---|---|
enum | string | the string value passed to the enum to be used as the key |
prevValue | any | the value of the previous enum initialized. Used to increment enum values |
Override syntax
In some cases you want a bit more control over the exact values on your enum. You can override the normal behavior of any given initializer by passing in an object rather than an array.
const enums = ; const colors = red: '#f44242' green: '#27c65a' blue: '#003bff' ;colorsred; // '#f44242'
This allows you to give values when running a function may not be the best method for defining the enum. You can also "opt-in" to the initializer whenever you want even when overriding by giving a key undefined
.
const enums string = ; const names = john: 'johnny' sarah: undefined tim: 'timothy' ;namessarah; // 'sarah'namestim; // 'timothy'
Objects and Arrays are invalid types for enum values and will be overwritten by default behavior when found.
Enums API
fun-enums
follows a similar API as defined by @rbuckton's enums impementing keys
, values
, entries
, has
, hasValue
, and getName
on each enum object.
.keys()
const enums = ; const colors = 'red' 'green' 'blue';colors; // ['red', 'green', 'blue']
.values()
const enums = ; const colors = 'red' 'green' 'blue';colors; // [0, 1, 2]
.entries()
const enums = ; const colors = 'red' 'green' 'blue';colors; // [['red', 0], ['green', 1], ['blue', 2]]
.has()
const enums = ; const colors = 'red' 'green' 'blue';colors; // truecolors; // false
.hasValue()
const enums = ; const colors = 'red' 'green' 'blue';colors; // truecolors; // false
.getName()
const enums = ; const colors = 'red' 'green' 'blue';colors; // 'red'colors; // undefined