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(ob) 
  {
    props=[];
    for (k in ob) if (ob.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.

Posted in JavaScript | 2 comments

Comments

    1. Avatar
      Ned Thu, 14 Oct 2010 20:54:38 GMT

      It looks like you’ve got a copy/paste error in your first snippet. “for (k in ht)” should probably be “for (k in obj)” now that the loop’s been moved to its own function.

    2. Avatar
      Jonas Elfström Fri, 15 Oct 2010 10:47:07 GMT

      Nice catch, fixed. Thanks!

Comments are closed