Created
April 24, 2022 18:23
-
-
Save WesleiRamos/d4bad68fc123307050decf676528cc49 to your computer and use it in GitHub Desktop.
hash table
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
class HashEntry { | |
constructor(k, v) { | |
this.key = k | |
this.value = v | |
} | |
setValue(v) { | |
this.value = v | |
} | |
} | |
class HashTable { | |
constructor(size = 20) { | |
this.size = size | |
this.table = [ ] | |
} | |
hash(key) { | |
return key.length % this.size | |
} | |
find(hash, k) { | |
if (!this.table[hash]) | |
return null | |
const length = this.table[hash].length | |
for (let i = 0; i < length; i++) { | |
if (this.table[hash][i].key === k) | |
return i | |
} | |
return null | |
} | |
remove(k) { | |
const hash = this.hash(k) | |
const index = this.find(hash, k) | |
if (index === null) | |
return false | |
this.table[hash].splice(index, 1) | |
} | |
get(k) { | |
const hash = this.hash(k) | |
const index = this.find(hash, k) | |
if (index === null) | |
return undefined | |
return this.table[hash][index].value | |
} | |
set(k, v) { | |
const hash = this.hash(k) | |
if (!this.table[hash]) | |
this.table[hash] = [ ] | |
const index = this.find(hash, k) | |
if (index === null) { | |
this.table[hash].push(new HashEntry(k, v)) | |
return true | |
} | |
this.table[hash][index].setValue(v) | |
return true | |
} | |
} | |
const table = new HashTable() | |
table.set('k', 20) | |
table.set('v', 40) | |
table.set('deeeeee', 80) | |
console.log(table.get('k'), table.get('v'), table.get('d')) | |
table.remove('k') | |
console.log(table.get('k')) | |
console.log(JSON.stringify(table.table)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment