Created
March 10, 2025 18:21
-
-
Save valterbarros/ab0a149e4ae0a5feab9fda6671af9227 to your computer and use it in GitHub Desktop.
hash map
This file contains hidden or 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
String.prototype.hashCode = function() { | |
var hash = 0, | |
i, chr; | |
if (this.length === 0) return hash; | |
for (i = 0; i < this.length; i++) { | |
chr = this.charCodeAt(i); | |
hash = ((hash << 5) - hash) + chr; | |
hash |= 0; // Convert to 32bit integer | |
} | |
return hash; | |
} | |
class HashMap { | |
constructor(size) { | |
this.buckets = Array.from({ length: size }, () => []); | |
this.size = size | |
} | |
_hash(key) { | |
return Math.abs(key.hashCode()) % this.size; | |
} | |
put(key, value) { | |
const index = this._hash(key); | |
const bucket = this.buckets[index]; | |
const has = bucket.some((item) => Object.keys(item).includes(key)); | |
if (has) return; | |
bucket.push({ [key]: value }); | |
} | |
} | |
const hm = new HashMap(10); | |
hm.put('valter', 20) | |
/* duplicated */ | |
hm.put('valter', 20) | |
hm.put('retlav', 20) | |
hm.put('Roberto', 30) | |
console.log(hm.buckets) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment