JS Swifty Enums

A convenient convention around "Enum" like things for Javascript

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
    // ============================================= //

    EnumType = function(rawValue) {
        /* 
        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.

        see: http://apple.co/1POMrMr for Swift Enum Ref
        */
        
        this._rawValue = rawValue;  
        
    };

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

    EnumType.prototype.getValue = function () {
        return this._associatedValue;
    };

    EnumType.prototype.setValue = function (value) {
        this._associatedValue = value;
    };

    // ============================================= //
    // Enumerate Utility Function
    // ============================================= //
    
    var enumerate = function(options) {
        /* 
        enumerate utility (above) lets us create a signature
        that comes as close to the Swifty type definition

        I went with a simple funciton for enumerate because
        it didn't make much sense to make a custom type
        just to make this look a little more OO.
        */
        
        return _.object(
            _.map(options, function (value, key, src) {
                return [key, new EnumType(value)];
            })
        );
    };

    exports.enumerate = enumerate;
    return exports;
})();

// ============================================= //
// Demo 
// ============================================= //

var Demo = (function(){

    var exports = {};
    
    exports.run = function() {
       ...