enumjs
A Enum class library in javascript.
quick start
define with string or string array
var OS = 'LINUX,WINDOWS'; // LINUX: 0, WINDOWS: 1var MOBILE = 'ANDROID' 'IOS'; // ANDROID: 0, IOS: 1 OSLINUX; // true+MOBILEIOS === 1; // true
The simplest way to create an Enum is using a string, in which you can change the seperators ,
with ;
or \s
. Or you can use an array to store your keys, which is recommanded.
define with object array
var PETS = key: 'DOG' name: 'DingDong' value: 100 key: 'CAT' name: 'Lily' value: 200 key: 'LIZARD' name: 'Keith' value: 300 ; // DOG: 100, CAT: 200, LIZARD: 300 PETSDOG; // DingDongPETS; // Keith
In some cases, you might connect your enum keys to some other info, so you can just create your enum with an Object array, storing your relative infomation with your enum keys.
You can name the custom property whatever you want, but you can only access the propery via the get
method, just like the javabean style, instead you cannot modify the property after defination.
usage
compare
The value of the Enum class is not a Number type, it cannot be compare to a number with ===
directly. Instead, method equals
or eq
is recommanded, or you can convert it to Number type explicitly.
var ENUMS = new 'A,B'; ENUMSA == 0; // true, not recommandedENUMSA === 0; // false+ENUMSA === 0; // trueENUMS === 0; // trueENUMS === 0; // trueENUMSA; // trueENUMSA; // true
get
The enum item can be accessed by it's value. An Enum item can
var GREETING = new key: 'ENGLISH' greeting: 'Hello' value: 100 key: 'DEUTSCH' greeting: 'Guten tag' value: 200 key: 'CHINESE' greeting: '你好' value: 300 ; GREETING; // GREETING.CHINESEGREETING; // 你好GREETINGCHINESE; // 你好GREETING; // 你好
forEach
GREETING;
map
var arr = GREETING;// [ 'ENGLISH', 'DEUTSCH', 'CHINESE' ]
filter
var TYPE = 'A,B,C';var arr = TYPE;// [TYPE.B, TYPE.C]
keys
var TYPE = 'A,B,C';var keys = TYPE;// ['A', 'B', 'C']
values
var TYPE = 'A,B,C';var keys = TYPE;// [0, 1, 2]
pick
var FRUIT = key: 'GRAPE' name: 'grape' color: 'purple' ; var grape = FRUITGRAPE// { name: 'grape', color: 'purple' }
pickAs
var FRUIT = key: 'GRAPE' name: 'grape' color: 'purple' ; var grape = FRUITGRAPE;// { fruit: 'grape', colour: 'purple' }