Background
Recently started a project that uses Facebook's Reactjs front-end framework. Find that you often use react's keymirror tool to define some enumeration constants:
var keyMirror = require(‘keyMirror‘);var AppMode = keyMirror({ LOG_IN: null, SIGN_UP: null});module.exports = AppMode;
The other JS code reference to the enumeration is probably the following code:
var AppMode = require(‘../const/app_mode‘);if (curMode == AppMode.LOG_IN) { ...} else { ...}...var className = (curMode == AppMode.LOG_IN) ? ‘login-form‘ : ‘signup-form‘;...
This kind of code feels OK, at least it's a lot better than the strings flying in the sky. But I found that there curMode == AppMode.LOG_IN were too many types of code, not very comfortable to write, and always asked me require(‘../const/app_mode‘) , and I wanted to be able to simply write code similar to that curMode.isLogIn() . So I got this simple tool Gen_enum:
Usage
npm install gen_enum
var createEnum = require(‘gen_enum‘);var COLORS = createEnum("blue red");var myColor = COLORS.blue;console.log(myColor._id); // output blueconsole.log(myColor.isBlue()); //output trueconsole.log(myColor.isRed()); //output falseconsole.log(myColor.name()); //output blueconsole.log(myColor.toString()); //output blue
Input:"key1 key2 ..."
Note that besides 空白 the keywords can also be used , , ; and : to split
Output:
{ key1: { _id: ‘key1‘, name: function() { return ‘key1‘; }, toString: function() { return ‘key1‘; }, isKey1: function() { return true; }, isKey2: function() { return false; } }, key2: { _id: ‘key2‘, name: function() { return ‘key2‘; }, toString: function() { return ‘key2‘; }, isKey1: function() { return false; }, isKey2: function() { return true; } }}
Other input forms
Using a string to specify the enumeration keyword is only one way, and gen_enum the other two forms of input are supported:
// 用字串数组来指定枚举关键字var Color = genEnum("blue", "red");var myColor = Color.blue;// 用Object对象来指定枚举关键字var WeekDay = genEnum({ Monday: null, Tuesday: null})var myDay = WeekDay.Monday;
About CamelCase
gen_enumConverts the function name of the uppercase underlined enumeration keyword isXXX to the CamelCase form:
var AppMode = genEnum(‘SIGN_UP, LOG_IN, FORGOT_PASSWORD‘);var curMode = AppMode.LOG_IN;console.log(curMode.isLogIn()); // 输出 trueconsole.log(curMode.isSignUp()); // 输出 falseconsole.log(curMode.isForgotPassword()); // 输出 false
Project Address:
- Https://github.com/greenlaw110/enumjs
- Https://www.npmjs.com/package/gen_enum
Emulating the enum of Java in JavaScript