Implementing HashTable in JavaScript

I found this as very usefull. Excellent work..

/**
    Created by: Michael Synovic
    on: 01/12/2003
   
    This is a Javascript implementation of the Java Hashtable object.
   
    Contructor(s):
     Hashtable()
              Creates a new, empty hashtable
   
    Method(s):
     void clear()
              Clears this hashtable so that it contains no keys.
     boolean containsKey(String key)
              Tests if the specified object is a key in this hashtable.
     boolean containsValue(Object value)
              Returns true if this Hashtable maps one or more keys to this value.
     Object get(String key)
              Returns the value to which the specified key is mapped in this hashtable.
     boolean isEmpty()
              Tests if this hashtable maps no keys to values.
     Array keys()
              Returns an array of the keys in this hashtable.
     void put(String key, Object value)
              Maps the specified key to the specified value in this hashtable. A NullPointerException is thrown is the key or value is null.
     Object remove(String key)
              Removes the key (and its corresponding value) from this hashtable. Returns the value of the key that was removed
     int size()
              Returns the number of keys in this hashtable.
     String toString()
              Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space).
     Array values()
              Returns a array view of the values contained in this Hashtable.
           
*/
function Hashtable(){
    this.clear = hashtable_clear;
    this.containsKey = hashtable_containsKey;
    this.containsValue = hashtable_containsValue;
    this.get = hashtable_get;
    this.isEmpty = hashtable_isEmpty;
    this.keys = hashtable_keys;
    this.put = hashtable_put;
    this.remove = hashtable_remove;
    this.size = hashtable_size;
    this.toString = hashtable_toString;
    this.values = hashtable_values;
    this.hashtable = new Array();
}

/*=======Private methods for internal use only========*/

function hashtable_clear(){
    this.hashtable = new Array();
}

function hashtable_containsKey(key){
    var exists = false;
    for (var i in this.hashtable) {
        if (i == key && this.hashtable[i] != null) {
            exists = true;
            break;
        }
    }
    return exists;
}

function hashtable_containsValue(value){
    var contains = false;
    if (value != null) {
        for (var i in this.hashtable) {
            if (this.hashtable[i] == value) {
                contains = true;
                break;
            }
        }
    }
    return contains;
}

function hashtable_get(key){
    return this.hashtable[key];
}

function hashtable_isEmpty(){
    return (parseInt(this.size()) == 0) ? true : false;
}

function hashtable_keys(){
    var keys = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            keys.push(i);
    }
    return keys;
}

function hashtable_put(key, value){
    if (key == null || value == null) {
        throw "NullPointerException {" + key + "},{" + value + "}";
    }else{
        this.hashtable[key] = value;
    }
}

function hashtable_remove(key){
    var rtn = this.hashtable[key];
    this.hashtable[key] = null;
    return rtn;
}

function hashtable_size(){
    var size = 0;
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            size ++;
    }
    return size;
}

function hashtable_toString(){
    var result = "";
    for (var i in this.hashtable)
    {     
        if (this.hashtable[i] != null)
            result += "{" + i + "},{" + this.hashtable[i] + "}\n";  
    }
    return result;
}

function hashtable_values(){
    var values = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null)
            values.push(this.hashtable[i]);
    }
    return values;
}

 

20 Comments

  • Cool. I'm glad other people are finding my code useful. Drop me a line at js@synovic{remove brackets}.com I'd love to hear how people are using the code in their projects.



    Mike



  • does it work in Netscape 6.1 or above as well ??

    i actually hate this browser i just ask cause some projects still use this

  • Hi
    The hashtable allows the user to add duplicate keys. Unlike c# hashtable, it doesn't check whether the key exists before adding it (and doesn't alert the user).

  • That's why you have to use the method containkey() before adding an element to the table, this way you make sure you don't override your value or have multiple keys, besides you shouldn't be comparing javascript to C#, you should be thankful there's an implementation at all for a hashtable in javascript

  • Hey dam good one, the code is understandable. Good one and keep itup, give more this kind of scripts

  • i want to j2ee book

  • Thanks. Great code. Gives me lots of ideas. It's a great learning tool too.

  • Muchas gracias por esta implementación de Hashtable en javascript! Me ha sido muy util

    thanks!!!

  • very nice....

    thank you.

  • Hello,

    Thanks a lot for such a wonderful code.
    Just keep up the good work.

  • a good hashtable class.

  • I have been using this code for several years now as writtin and worked fine. Recently, it stopped and I can't figure out why. Now when you instantiate the class (i know), in my case it has 40 initial entries in the hashtable: "each", "eachSlice", "any", "all", etc. When I add new entries, they go to the top of the list but I can't iterate thru it anymore by getting keys() and values(). Any idea why this behavior has recently changed? Same happens in IE 6 and FF 2.

    Weird.

  • OK! Found the problem. Sorry Michael, this does not work in conjunction w/ Ajax. Since Ajax overloads the Array object, all the array functionality breaks. I am trying to figure out a way around it. If I do, I will be happy to post it.

  • After many hours, of doing many different and ornate coding changes, got a very basic solution from the prototype IRC group:

    replace the two instances of

    this.hashtable = new Array();

    with

    this.hashtable = {};

    Still works like the normal javascript array but without the overloaded Ajax functionality.

    Hope this helps others as well.

  • Whoops. I noticed the comments needed to be tweaked. Maybe the moderator can remove the code from my last post :)

    /**
    Created by: Michael Synovic;
    on: 01/12/2003

    This is a Javascript implementation of the Java Hashtable object.

    Copyright (C) 2003 Michael Synovic

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
    Lesser General Public License for more details.

    Contructor(s):
    Hashtable()
    Creates a new, empty hashtable

    Method(s):
    void clear()
    Clears this hashtable so that it contains no keys.
    boolean containsKey(String key)
    Tests if the specified object is a key in this hashtable.
    boolean containsValue(Object value)
    Returns true if this Hashtable maps one or more keys to this value.
    Object get(String key)
    Returns the value to which the specified key is mapped in this hashtable.
    boolean isEmpty()
    Tests if this hashtable maps no keys to values.
    Array keys()
    Returns an array of the keys in this hashtable.
    void put(String key, Object value)
    Maps the specified key to the specified value in this hashtable. A NullPointerException is thrown is the key or value is null.
    Object remove(String key)
    Removes the key (and its corresponding value) from this hashtable. Returns the value of the key that was removed
    int size()
    Returns the number of keys in this hashtable.
    String toString()
    Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space).
    Array values()
    Returns a array view of the values contained in this Hashtable.
    Array entrySet()
    Returns a reference to the internal object that stores the data. The object is backed by the Hashtable, so changes to the Hashtable are reflected in the object, and vice-versa.

    */
    function Hashtable(){
    this.hashtable = new Object();
    }

    /* privileged functions */

    Hashtable.prototype.clear = function(){
    this.hashtable = new Object();
    }
    Hashtable.prototype.containsKey = function(key){
    var exists = false;
    for (var i in this.hashtable) {
    if (i == key && this.hashtable[i] != null) {
    exists = true;
    break;
    }
    }
    return exists;
    }
    Hashtable.prototype.containsValue = function(value){
    var contains = false;
    if (value != null) {
    for (var i in this.hashtable) {
    if (this.hashtable[i] == value) {
    contains = true;
    break;
    }
    }
    }
    return contains;
    }
    Hashtable.prototype.get = function(key){
    return this.hashtable[key];
    }
    Hashtable.prototype.isEmpty = function(){
    return (parseInt(this.size()) == 0) ? true : false;
    }
    Hashtable.prototype.keys = function(){
    var keys = new Array();
    for (var i in this.hashtable) {
    if (this.hashtable[i] != null)
    keys.push(i);
    }
    return keys;
    }
    Hashtable.prototype.put = function(key, value){
    if (key == null || value == null) {
    throw "NullPointerException {" + key + "},{" + value + "}";
    }else{
    this.hashtable[key] = value;
    }
    }
    Hashtable.prototype.remove = function(key){
    var rtn = this.hashtable[key];
    this.hashtable[key] = null;
    return rtn;
    }
    Hashtable.prototype.size = function(){
    var size = 0;
    for (var i in this.hashtable) {
    if (this.hashtable[i] != null)
    size ++;
    }
    return size;
    }
    Hashtable.prototype.toString = function(){
    var result = "";
    for (var i in this.hashtable)
    {
    if (this.hashtable[i] != null)
    result += "{" + i + "},{" + this.hashtable[i] + "}\n";
    }
    return result;
    }
    Hashtable.prototype.values = function(){
    var values = new Array();
    for (var i in this.hashtable) {
    if (this.hashtable[i] != null)
    values.push(this.hashtable[i]);
    }
    return values;
    }
    Hashtable.prototype.entrySet = function(){
    return this.hashtable;
    }

  • Hi,
    I was looking for a Hashtable in javascript. First try was to use associative arrays, perfect solution in IE, not working in FireFox. Then I have found this Hashtable ... the same story unfortunatelly, works in IE but not in FireFox ... Does anybody know how to make it work ?
    Thanks, Jan

  • I do apologize, it works in Firebox, I had a bug somewhere else in javascript.
    Jan

  • dugun davetiyesi, sünnet davetiyesi, sünnet, davetiye, davetiye resimleri, davetiye örnekleri

  • Superb Atricle. This helped me a Lot to Improve Javascript.

  • remove this it is a cincom.com copyright code

Comments have been disabled for this content.