Javascript Hashmap

Posted: 8 July 2009 in Javascript
Tags: ,

The hashmap concept in javascript does not exist natively. Below you will find some code of an HashMap implementation using prototypes. I have had to create this to do encoding and decoding of HTML entities in teamsite datacapture forms. Save the code in a javascript file (I named my file HashMap.class.js).

function HashMap(){
    HashMap.prototype.keys = new Array();
    HashMap.prototype.values = new Array();
}
/* HashMap get function */
HashMap.prototype.get= function(key){
    for (var index=0; index < this.keys.length; index++){
        if (key==this.keys[index]){
            return(this.values[index]);
        }
    }
    return(null);
}
/* HashMap put function */
HashMap.prototype.put = function(key, value){
    this.keys[this.keys.length] = key;
    this.values[this.values.length] = value;
}
/* HashMap containsKey function */
HashMap.prototype.containsKey= function(key){
    for (var index=0; index < this.keys.length; index++){
        if (key==this.keys[index]){
            return(true);
        }
    }
    return(false);
}
/* HashMap debug function */
HashMap.prototype.debug = function(){
    var debug="";
    for (var index=0; index < this.keys.length; index++){
        var key=this.keys[index];
        var value=this.values[index];
        debug+=key + "->" + value + "\n";
    }
    return(debug);
}
/* HashMap size function */
HashMap.prototype.size = function(){
    return(this.keys.length);
}
/* HashMap containsKey function */
HashMap.prototype.containsValue= function(values){
    for (var index=0; index < this.values.length; index++){
        if (values==this.values[index]){
            return(true);
        }
    }
    return(false);
}

Note: this Hashmap implementation is not complete, even though it was sufficient for me and could (should) implement additional methods (for example, it doesn’t have a remove method).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s