Skip to content

Instantly share code, notes, and snippets.

@texdc
Last active August 29, 2015 14:21
Show Gist options
  • Save texdc/965b1d95f1e42abf80fd to your computer and use it in GitHub Desktop.
Save texdc/965b1d95f1e42abf80fd to your computer and use it in GitHub Desktop.
Type-Safe Enum in Javascript
var FilterType = (function() {
'use strict';
var _type = function(type) {
Object.defineProperties(this, {
toString: { value: function() {
return type;
}},
eq: { value: function(another) {
return type === another.toString();
}}
});
};
return Object.create(Object.prototype, {
AND: { value: new _type("AND"); },
OR: { value: new _type("OR"); }
});
})();
'use strict';
var Role = function(id) {
Object.defineProperty(this, 'Id', { value: id });
};
Role.prototype = Object.create(Object.prototype, {
toString: { value: function() {
return this.Id;
}},
hasValue: { value: function(value) {
if (typeof value === "string") {
return this.Id === value;
}
return this === value;
}}
});
Role.prototype.constructor = Role;
Object.defineProperties(Role, {
GUEST: { value: new Role('Guest') },
MEMBER: { value: new Role('Member') },
ADMIN: { value: new Role('Admin') }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment