Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Javascript Enum
/**
* Make a bag of string constants, kind of like a Java enum.
* e.g. var Kind = new Enum('TEXT PERSON');
* gives you Kind.TEXT == 'TEXT', Kind.PERSON = 'PERSON'
*
* Each of the constants has an isCONSTANT() function added, so you can write:
* Kind.isTEXT(myvar) -- which has the advantage that it will create a noisy error if
* Kind.TEXT ceased to be a valid value, or if myvar is invalid.
*
* Use-case: It's safer than using strings for constants, especially around refactoring.
*
* @param values {string|string[]}
* @constructor
* @author Daniel
* Ref: http://stijndewitt.wordpress.com/2014/01/26/enums-in-javascript/
*/
function Enum(values) {
if (typeof(values)==='string') {
values = values.split(' ');
}
for(var i=0; i<values.length; i++) {
var k = values[i];
this[k] = k;
this['is'+k] = function(v) {
if ( ! this.enum[v]) throw 'Invalid Enum value: '+v;
return v===this.k;
}.bind({enum:this, k:k});
}
// Prevent edits, if we can
if (Object.freeze) {
Object.freeze(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment