Skip to content

Instantly share code, notes, and snippets.

@SparrowMike
Last active November 17, 2022 15:23
Show Gist options
  • Save SparrowMike/2c68d98f5c265c53169a42330aa5a3eb to your computer and use it in GitHub Desktop.
Save SparrowMike/2c68d98f5c265c53169a42330aa5a3eb to your computer and use it in GitHub Desktop.
// Seperate Chaining
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
}
set(key, value) {
var hashedKey = this._hash(key)
if (!this.keyMap[hashedKey]) {
this.keyMap[hashedKey] = []
}
this.keyMap[hashedKey].push([key, value])
return this.keyMap;
}
get(key) {
var hashedKey = this._hash(key)
if (this.keyMap[hashedKey]) {
for (let i of this.keyMap[hashedKey]) {
if (i[0] === key) return i[1]
}
}
return undefined;
}
keys() {
const arr = [];
for (let keys of this.keyMap) {
if (keys) {
for (let key of keys) {
if (!arr.includes(key[0])) {
arr.push(key[0]);
}
}
}
}
return arr;
}
values() {
const arr = [];
for (let keys of this.keyMap) {
if (keys) {
for (let key of keys) {
if (!arr.includes(key[1])) {
arr.push(key[1]);
}
}
}
}
return arr;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment