JavaScript hash table keys

Posted by Jonas Elfström Fri, 05 Mar 2010 16:42:00 GMT

In JavaScript you can add properties to objects dynamically. You can access those properties both by object.foo and object['foo']. The later is commonly used to use JavaScript objects as hash tables (associative arrays).

While implementing a simplistic unique random number generator I happened to use keys(obj). Unfortunately keys(obj) is part of ECMAScript 5. See chapter 15.2.3.14 in ECMA-262. The web browsers of today mostly implements ECMAScript 3.

Here's an implementation of keys(obj) for ECMAScript 3 browsers (tested in Google Chrome, IE8 and Firefox 3.5). If the browser already has a keys function then nothing will be done.

1
2
3
4
5
6
7
8
9
if (typeof keys == "undefined") 
{ 
  var keys = function(obj) 
  {
    props=[];
    for (k in ht) if (ht.hasOwnProperty(k)) props.push(k);
    return props;
  }
}


The simplistic unique random number generator looks like this

1
2
3
4
5
6
function uniqueRndNumbers(min, max, quantity) {
  var ht={}, i=quantity;
  while ( i>0 || keys(ht).length<quantity) 
    ht[Math.floor(Math.random()*(max-min+1))+min]=i--;
  return keys(ht);
}


This function has not undergone any serious testing. Also if the quantity is more than a fraction of (max-min) then another algorithm like the Fisher–Yates shuffle might be a better choice.