Skip to content

Instantly share code, notes, and snippets.

@lnt
Created December 26, 2018 06:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lnt/bb13a2fd63cdb8bce85fd62965a20026 to your computer and use it in GitHub Desktop.
Save lnt/bb13a2fd63cdb8bce85fd62965a20026 to your computer and use it in GitHub Desktop.
Enum in JavaScript
var Enum = (function(foo) {
var EnumItem = function(item){
if(typeof item == "string"){
this.name = item;
} else {
this.name = item.name;
}
}
EnumItem.prototype = new String("DEFAULT");
EnumItem.prototype.toString = function(){
return this.name;
}
EnumItem.prototype.equals = function(item){
if(typeof item == "string"){
return this.name == item;
} else {
return this == item && this.name == item.name;
}
}
function Enum() {
this.add.apply(this, arguments);
Object.freeze(this);
}
Enum.prototype.add = function() {
for (var i in arguments) {
var enumItem = new EnumItem(arguments[i]);
this[enumItem.name] = enumItem;
}
};
Enum.prototype.toList = function() {
return Object.keys(this);
};
foo.Enum = Enum;
return Enum;
})(this);
var STATUS = new Enum("CLOSED","PENDING", { name : "CONFIRMED", ackd : true });
var STATE = new Enum("CLOSED","PENDING","CONFIRMED",{ name : "STARTED"},{ name : "PROCESSING",});
assert("Diff Enumes with equalSign",false, STATE.CLOSED === STATUS.CLOSED); // false;
assert("Compare with String",false, STATE.CLOSED === "CLOSED" ); // false;
assert("Compare String Value",true, STATE.CLOSED.toString() === "CLOSED" ); // false;
STATE.PENDING = "NOT_PENDING";
assert("Value cannot be changed",true, STATE.PENDING.toString() === "PENDING" ); // false;
assert("Same String value with equals method",true, STATE.PENDING.equals("PENDING") );
assert("Diff String value with equals method",false, STATE.PENDING.equals("CLOSED") );
assert("Same Enums with equals method",true, STATE.PENDING.equals(STATE.PENDING) );
assert("Diff Enums with equals method",false, STATE.PENDING.equals(STATUS.PENDING) );
function assert(test,expression,result){
console.log("Result : ", expression == result, "=>\tfor", test);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment