JS Swifty Enums v2

A convenient convention around "Enum" like things for Javascript. This second version follows more closely the Swift Enum api.

by Aubrey Taylor

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<p>Pop open the console with: <b class="highlight">⌘ + Shift + i</b></p>
<button class="js-run-btn">Run Demo</button>

CSS

body {
    font-family: sans-serif;
}

.highlight {
    background: cyan;   
}
}

JavaScript

// ============================================= //
// Enums Pseudo Module Definition
// ============================================= //

var Enums = (function(){
    
    var exports = {};

    // ============================================= //
    // EnumType Type Definition
    // ============================================= //

    // Api is modeled largely after Swift enums
    // Of course JS as it is offers no real immutability, 
    //   but I like how convenient Swift Enums are
    //   and thought this might be a nice convention for 
    //   "Enum" like things.

    var EnumValue = function(namedParams) {
        namedParams = namedParams || {};

        this._rawValue = namedParams.rawValue;
        this._value = namedParams.value;
        this._key = namedParams.key;
    };
    
    EnumValue.extend = function() {
        // super simple extend
        // see: http://stackoverflow.com/a/10430875
        
        var Type = function(namedParams) {
            EnumValue.call(this, namedParams);
        }
        
        Type.prototype = EnumValue.prototype;
        Type.prototype.constructor = Type;
        
        return Type;
    };

    EnumValue.prototype.getValue = function () {
        return this._value;
    };

    EnumValue.prototype.getRawValue = function () {
        return this._rawValue;
    };

    EnumValue.prototype.value = function () {
        // special sugar method to make getting value more convenient
        return this._rawValue || this._value;
    };
    
    EnumValue.prototype.toString = function () {
        return this._key;
    };

    var EnumType = function(options, ValueType) {
        this.ValueType = ValueType || EnumValue;
        _.extend(this, this.enumerate(options));
    };

    EnumType.prototype.enumerate = function(options) {
        if(_.isArray(options)) return this.enumerateAssociative(options);
        if(_.isObject(options)) return this.enumerateRaw(options);
    };

   ...