Custom implementation of hashMap in javascript

Introduction

var obj = {      name:'ujjwal gupta'
}

Let’s Code

getHash(value) {
value = value.toString();
let sum = 0;
for (var i = 0, len = value.length; i < len; i++) {
sum += value.charCodeAt(i);
}
return sum;
}
class HashMap {
constructor() {
this.store = [];
}
getHash(value) {
value = value.toString();
let sum = 0;
for (var i = 0, len = value.length; i < len; i++) {
sum += value.charCodeAt(i);
}
return sum;
}
set(key, value) {
const hashValue = this.getHash(key);
this.store[hashValue] = value;
}
get(key) {
const hashValue = this.getHash(key);
return this.store[hashValue];
}
isExist(key) {
const hashValue = this.getHash(key);
return this.store[hashValue] != null;
}
remove(key) {
const hashValue = this.getHash(key);
this.store[hashValue] = null;
}
}
const map = new HashMap();
map.set(5, 100);
map.set(8, 200);
console.log(map.get(5));
console.log(map.get(8));
class Node {
constructor(key, value) {
this.key = key;
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.data = null;
}
set(key, value) {
const node = new Node(key, value);
if (this.root == null) {
this.root = node;
} else {
let root = this.root;
while (root.next != null) {
if (root.key === key) {
root.value = value;
return;
}
root = root.next;
}
root.next = node;
}
}
get(key) {
let root = this.root;
while (root != null) {
if (root.key === key) {
return root.value;
}
root = root.next;
}
return null;
}
}
class HashMap {
constructor() {
this.store = [];
}
getHash(value) {
value = value.toString();
let sum = 0;
for (var i = 0, len = value.length; i < len; i++) {
sum += value.charCodeAt(i);
}
return sum;
}
set(key, value) {
const hashValue = this.getHash(key);
if (this.store[hashValue] == null) {
this.store[hashValue] = new LinkedList();
}
// add or update key,value to linked list
this.store[hashValue].set(key, value);
}
get(key) {
const hashValue = this.getHash(key);
if (this.store[hashValue]) {
return this.store[hashValue].get(key);
}
return null;
}
isExist(key) {
const hashValue = this.getHash(key);
return this.store[hashValue] != null;
}
remove(key) {
const hashValue = this.getHash(key);
this.store[hashValue] = null;
// Note :- here removing will remove all values which is not a good solution
// we will have to use double linked list in order to remove a value from linked list
// I am not doing here, to make program simple
}
}
const map = new HashMap();
map.set("lies", 100);
map.set("foes", 200);
console.log(map.get("lies")); // 100
console.log(map.get("foes")); // 200

References

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ujjwal Gupta

Ujjwal Gupta

105 Followers

Frontend lead Polygon | Creator of jsstore, mahaljs | sqlweb, fortjs | opensource creator | we3, blockchain, solidity | javascript