Last active
August 29, 2015 14:21
-
-
Save texdc/965b1d95f1e42abf80fd to your computer and use it in GitHub Desktop.
Type-Safe Enum in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); } | |
}); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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