Last active
November 17, 2022 15:23
-
-
Save SparrowMike/2c68d98f5c265c53169a42330aa5a3eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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