標籤:
背景
最近開始做的一個項目使用facebook的ReactJS前端架構。發現經常使用react的keyMirror工具來定義一些枚舉常量:
var keyMirror = require(‘keyMirror‘);var AppMode = keyMirror({ LOG_IN: null, SIGN_UP: null});module.exports = AppMode;
其他JS代碼對該枚舉的引用大概如下代碼:
var AppMode = require(‘../const/app_mode‘);if (curMode == AppMode.LOG_IN) { ...} else { ...}...var className = (curMode == AppMode.LOG_IN) ? ‘login-form‘ : ‘signup-form‘;...
這樣的代碼感覺還行,起碼比字串漫天飛舞的情況好很多。不過我發現諸如curMode == AppMode.LOG_IN類型的代碼太多了,寫起來不太舒服,而且總是要求我require(‘../const/app_mode‘),我希望能簡單地寫類似於curMode.isLogIn()的代碼。所以就搞了這個簡單的工具gen_enum:
用法
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
輸入: "key1 key2 ..."
注意,除空白以外關鍵字還可以用,, ; 以及:來分割
輸出:
{ 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; } }}
其他輸入形式
使用字串來指定枚舉關鍵字只是一種方式,gen_enum還支援其他兩種形式的輸入:
// 用字串數組來指定枚舉關鍵字var Color = genEnum("blue", "red");var myColor = Color.blue;// 用Object對象來指定枚舉關鍵字var WeekDay = genEnum({ Monday: null, Tuesday: null})var myDay = WeekDay.Monday;
關於 CamelCase
gen_enum將大寫加底線的枚舉關鍵字的isXXX函數名轉換為CamelCase形式:
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
項目地址:
- https://github.com/greenlaw110/enumjs
- https://www.npmjs.com/package/gen_enum
在JavaScript中模擬Java的enum