Ordered Hash Class

by ariehg

JavaScript

var OHash = function(obj){
    this.keys = {};
    this.values = [];
    this.length = 0;
    
    if (obj)
        for (var k in obj) if (obj.hasOwnProperty(k)) this.set(k,obj[k]);
};

OHash.prototype = {
    set: function set(key,val){
        this.keys[key] = this.length++;
        this.values.push(val);
    }
    , get : function get(key){
        return (this.keys[key]) ? this.values[this.keys[key]] : null;
    }
    , getByIndex : function(i){
        if (i == 'first') return this.values[0];
        if (i == 'last') return this.values[this.length-1];
        if (i in this.values) return this.values[i];
        return null;
    }
    , erase : function(key){
        if (this.keys[key]) {
            this.values.splice(this.keys[key],1);
            delete this.keys[key];
            this.length--;
        }
        return this;
    }
};


var h = new OHash({
    'a' : 'b'
    , 'c' :'d'
    , 'e' : 'f'
});

console.log(h.length);
console.log(h.getByIndex('first'));
console.log(h.getByIndex(1));
console.log(h.getByIndex('last'));
h.set('g','h');
console.log(h.length);
console.log(h.getByIndex('last'));
h.erase('c');
console.log(h.length);