Ordered hash in JavaScript

@Vardhan 's answer in plain JavaScript, using closure instead of classical OO and adding an insert() method:

function makeOrderedHash() {
    let keys = [];
    let vals = {};
    return {
        push: function(k,v) {
            if (!vals[k]) keys.push(k);
            vals[k] = v;
        },
        insert: function(pos,k,v) {
            if (!vals[k]) {
                keys.splice(pos,0,k);
                vals[k] = v;
            }
        },
        val: function(k) {return vals[k]},
        length: function(){return keys.length},
        keys: function(){return keys},
        values: function(){return vals}
    };
};

let myHash = makeOrderedHash();

JavaScript in 2016, specifically EcmaScript 6, supports the Map built-in class.

A Map object iterates its elements in insertion order — a for...of loop returns an array of [key, value] for each iteration.

That's what you need. (I wonder why that is the first info in the description of this data structure, though.)

For example,

m = new Map()

m.set(3,'three')
m.set(1,'one')
m.set(2,'two')

m // Map { 3 => 'three', 1 => 'one', 2 => 'two' }

[...m.keys()] // [ 3, 1, 2 ]

or the example from the docs:

var myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');

myMap // Map { 0 => 'zero', 1 => 'one' }

for (var [key, value] of myMap) {
  console.log(key + " = " + value);
}

for (var key of myMap.keys()) {
  console.log(key);
}

for (var value of myMap.values()) {
  console.log(value);
}

for (var [key, value] of myMap.entries()) {
  console.log(key + " = " + value);
}

No, since the Object type is specified to be an unordered collection of properties, you can not rely on that. (Or: You can only rely on that an object is an unordered collection of properties.)

If you want to have an ordered hash set, you will need to implement it on your own.

Tags:

Javascript