class HashTable {
constructor(size=53){
this.keyMap = new Array(size);
}
_hash(key) {
let total = 0;
let WEIRD_PRIME = 31;
for (let i = 0; i < Math.min(key.length, 100); i++) {
let char = key[i];
let value = char.charCodeAt(0) - 96
total = (total * WEIRD_PRIME + value) % this.keyMap.length;
}
return total;
}
// Add a Value
set(key, value) {
let index = this._hash(key);
if(!this.keyMap[index]) {
this.keyMap[index] = [];
}
this.keyMap[index].push([key, value]);
console.log(` ${key} or ${value} ->> is added successfully 👍👍`)
return ht;
}
// Find a value
get(key) {
let index = this._hash(key);
if(this.keyMap[index]) {
for(let i = 0; i < this.keyMap[index].length; i++) {
if(this.keyMap[index][i][0] === key) {
return this.keyMap[index][i][1]
}
}
}
return undefined;
}
// Show all Keys
keys() {
let keysArr = [];
for(let i = 0; i <this.keyMap.length; i++) {
if(this.keyMap[i]) {
for( let j = 0; j < this.keyMap[i].length; j++) {
if(!keysArr.includes(this.keyMap[i][j][0])) {
keysArr.push(this.keyMap[i][j][0])
}
}
}
}
console.log(` Your Keys is -> ${keysArr}`);
return keysArr;
}
// Show all Value
value() {
let valuesArr = [];
for(let i = 0; i <this.keyMap.length; i++) {
if(this.keyMap[i]) {
for( let j = 0; j < this.keyMap[i].length; j++) {
if(!valuesArr.includes(this.keyMap[i][j][1])) {
valuesArr.push(this.keyMap[i][j][1])
}
}
}
}
console.log(` Your Value is -> ${valuesArr}`)
return valuesArr;
}
}
let ht = new HashTable(17);
ht.set("java script ", "java")
ht.set("html ", "css")
ht.set("c ", "c++")
ht.value();
ht.keys();
// ht.keys().forEach(function(key) {
// console.log(` -> your Key is -> ${ht.get(key)}`);
// })
// 👆👆 👆 👆 👆 👆 👆 👆 👆
// 👉 OUTPUT 👈
// -> your Key is -> java
// -> your Key is -> css
// -> your Key is -> c++
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)