Skip to content

Instantly share code, notes, and snippets.

@winterstein
Created February 3, 2014 09:56
Show Gist options
  • Save winterstein/8781207 to your computer and use it in GitHub Desktop.
Save winterstein/8781207 to your computer and use it in GitHub Desktop.
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