Skip to content

Instantly share code, notes, and snippets.

@dtx
Created September 27, 2012 00:11
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dtx/3791420 to your computer and use it in GitHub Desktop.
Save dtx/3791420 to your computer and use it in GitHub Desktop.
A simple HashMap implementation in Javascript, just something I wrote while reading DailyJS.
var HashMap = function(){
this._size = 0;
this._map = {};
}
HashMap.prototype = {
put: function(key, value){
if(!this.containsKey(key)){
this._size++;
}
this._map[key] = value;
},
remove:function(key){
if(this.containsKey(key)){
this._size--;
var value = this._map[key];
delete this._map[key];
return value;
}
else{
return null;
}
},
containsKey: function(key){
return this._map.hasOwnProperty(key);
},
containsValue: function(value){
for(var key in this._map){
if(this._map.hasOwnProperty(key)){
if(this._map[key] === value){
return true;
}
}
}
return false;
},
get: function(key){
return this.containsKey(key) ? this._map[key] : null;
},
clear: function(key){
this.size = 0;
this._map= {};
},
keys: function(){
var keys = [];
for(var keys in this._map){
if(this._map.hasOwnProperty(key)){
keys.push(key);
}
}
return keys;
},
values: function(){
var values[];
for(var key in this._map){
if(this._map.hasOwnProperty(key)){
values.push(this._map[key]);
}
}
},
size: function(){
return this._size;
}
};
@tehpsalmist
Copy link

Nice work, thanks for putting this out into the ether!

Unrelated to my compliment, I think line 62 is missing an =. :)

@PadCesar
Copy link

PadCesar commented Dec 14, 2018

Hello, thank you for the code.
Just add return inside "values" function.
And in function "keys" the for loop variable is key
for(var key in this._map)

@juanmendes
Copy link

How is this a hash map if there's no hashing/equals checks?

Copy link

ghost commented Jan 4, 2020

You are writing a HashMap, with a HashMap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment