two-way key-value dictionary

by plus5keen

HTML

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        <h2>Output</h2>
        <div class="output"></div>
        <p>output goes to development console</p>
    </body>
</html>

JavaScript

// AMD-to-global shim
function amdToGlobal(global, key) {
    if (!global || global.define) { return; }

    var oldDefine = global[key];

    global[key] = global.define;
    global.define = function(cb) { // TODO add deps?
        global[key] = cb();
        global.define = oldDefine;
    };
}

amdToGlobal(window, 'KeyVal');

define(function() {
    'use strict';
    
    function KeyVal(pairs) {
        this._kv = {};
        this._vk = {};
        this.addPairs(pairs);
    }
    
    KeyVal.prototype = {
        kv: function (key) {
            return this._kv[key];
        },
        vk: function (value) {
            return this._vk[value];
        },
        addPair: function (key, value) {
            this._kv[key] = value;
            this._vk[value] = key;
        },
        addPairs: function (pairs) {
            var self = this;
    
            _.each(pairs, function (value, key) {
                self.addPair(key, value);
            });
        }
    };

    return KeyVal;

});

true && (function(KeyVal) {
    'use strict';

    //var $output = $('.output');

    function log(text) {
        //$output.append($('<div>').text(text));
        console.log.apply(console, arguments);
    }

    var ts = [], i;

    log('beginning test');

    log('creating Test class');

    ts.push(new KeyVal({
        a: 'x',
        b: 'y',
        c: 'z'
    }));

    log('beginning test operations');

    _.each(ts, function (t, i) {
        log('running test operations on keyval #' + i);
        log(t);
        
        log('lookup on value x: ', t.vk('x'));
        log('lookup on key c: ', t.kv('c'));
        log('lookup on value y: ', t.vk('y'));
        log('lookup on key a: ', t.kv('a'));
        log('lookup on value z: ', t.vk('z'));
        log('lookup on key b: ', t.kv('b'));
    });

    log('finishing test');

}(KeyVal));