A utility library for working with enumerated types (enums). Simplify the management of constant values by creating strongly-typed enums with custom labels and values. Provides convenience methods for enum conversion, retrieval, and equality checks.
Inspired by PHP Enum.
npm install @ngekoding/enumThis is how an enum can be defined.
importEnumfrom'@ngekoding/enum'classUserLevelextendsEnum{staticBasic=newUserLevel(1,'Basic')staticPro=newUserLevel(2,'Pro')staticPremium=newUserLevel(3,'Premium')}Where the first parameter is the value and the second parameter is the label.
console.log(UserLevel.Basic.value)// Output: 1console.log(UserLevel.Basic.label)// Output: BasicconstuserLevel=UserLevel.fromValue(2)When an enum value doesn't exist, you'll get an Error exception. If you would prefer not catching an exception, you can use:
constuserLevel=UserLevel.tryFromValue(2)When an enum value doesn't exist in this case, userLevel will have value null and label Unknown.
Enums can be compared using the equals method:
console.log(userLevel.equals(UserLevel.Pro))// Output: trueYou can pass several enums to the equals method, it will return true if the current enum equals one of the given values.
console.log(userLevel.equals(UserLevel.Pro,UserLevel.Premium))// Output: trueYou can safely comparing enum even there is no enum value when using tryFromValue.
console.log(UserLevel.tryFromValue(0).equals(UserLevel.Basic))// Output: falseYou can get an array containing all the enum instances defined within the enum class. This is allows easy access to the entire set of enum values.
constvalues=UserLevel.values()console.log(values)// Output: [UserLevel.Basic, UserLevel.Pro, UserLevel.Premium]