I am trying to implement hashmap functionality in JavaScript and want to keep everything in constant time.
Problem 1: Remove element from array in constant time (O(1)) And I am using array.
Problem 2: Best way to resolve collision problem in case we same hash for different keys.
Problem 3: Best way to create hashcode. Currently I am using some of ASCII values of each character.
Code example
class myHashMap {
constructor(size = 0 ){
if(size){
this.hashMap = new Array(size).fill(null);
this.size = size;
}
else{
this.hashMap = new Array();
this.size = 0;
}
}
hash(key){
// Here hashing can have collision
//for example: 122 and 212 will have same hash which is not correct
let CharArray = key.split("");
return CharArray.reduce((acc,current) => {
return acc+current.charCodeAt(0);
},0);
}
set(key,value)
{
this.size++;
this.hashMap[this.hash(key)] = value;
}
get(key){
return this.hashMap[key];
}
has(key){
return this.hashMap[key];
}
remove(key)
{
this.size--;
this.hashMap.splice(this.hash(key),1);
// Here I need to remove element in O(1)
}
}