Skip to content

Instantly share code, notes, and snippets.

@gfarrell
Last active December 24, 2015 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gfarrell/6716853 to your computer and use it in GitHub Desktop.
Save gfarrell/6716853 to your computer and use it in GitHub Desktop.
Create Enums in Javascript (immutable dictionaries of string:int pairings).
/* global define */
/**
* Enums in Javascript
*
* Makes an immutable dictionary with string:int pairings to emulate Enums.
* Usage example: Colours = Enum('RED', 'GREEN', 'BLUE');
*
* @author Gideon Farrell <me@gideonfarrell.co.uk>
*
*/
define(function() {
'use strict';
var Enum = function() {
var e = {}, // the enumerator object
args = Array.prototype.slice.apply(arguments),
count = args.length;
// Iterate over the args, and add them as enum keys
var index = 1;
for(var i = 0; i < count; i++) {
var key = args[i];
if(e.hasOwnProperty(key)) {
continue;
} else {
if(typeof Object.defineProperty == 'function') {
// Javascript 1.8.5, use defineProperty
Object.defineProperty(e, key, {configurable: false, enumerable: true, value: index, writable: false});
} else if(typeof e.__defineGetter__ == 'function' && typeof e.__defineSetter__ == 'function') {
// This is non-standard, but we'll use it if defineProperty fails
// (it has to be present though)
e.__defineGetter__(key, function() { return index; });
e.__defineSetter__(key, function() { return false; });
} else {
// if all else fails, it won't be immutable, but we'll be graceful about it
e[key] = index;
}
index++;
}
}
return e;
};
return Enum;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment