JSFiddle - React, Tailwind, and code Playground
by Shridhar Baddur
JavaScript
class HashTable {
constructor(size){
this.data = new Array(size);
}
// _hash(key) {
// let hash = 0;
// for (let i =0; i < key.length; i++){
// hash = (hash + key.charCodeAt(i) * i) % this.data.length
// }
// return hash;
// }
_hash(key) {
let hash = 0;
for(let i = 0; i < key.length; i++) {
hash = (hash + key.charCodeAt(i) * i) % this.data.length;
}
return hash;
}
set(key, value) {
let address = this._hash(key);
let isAvailable = this.get(key);
debugger;
if(isAvailable) {
this.data[address][0][1] = value;
return;
}
if (!this.data[address]) {
this.data[address] = [];
}
this.data[address].push([key, value]);
return this.data;
}
get(key) {
let address = this._hash(key);
let currentBucket = this.data[address];
if(currentBucket) {
for(let i = 0; i < currentBucket.length; i++) {
if(currentBucket[i][0] === key) {
return currentBucket[i][1]
}
}
}
return undefined;
}
}
const myHashTable = new HashTable(2);
myHashTable.set('grapes', 10000)
myHashTable.set('grapes', 20000)
// console.log(myHashTable.get('grapes'))
myHashTable.set('apples', 9)
// console.log(myHashTable.get('apples'))
console.log(myHashTable.get('grapes'))
console.log(myHashTable.get('apples'))
// console.log(myHashTable)