Created
January 18, 2021 23:52
-
-
Save FelixLuciano/c77d9287dc4dafb2b63397b79b9a73f2 to your computer and use it in GitHub Desktop.
rendezvous with cassidoo #179 - Interview question of the week
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
//Design a hashmap without using any built-in libraries. You should include the following functions: | |
// - put(key, value): Insert a (key, value) pair into the hashmap. If the value already exists, update the value. | |
// - get(key): Returns the value to which key is mapped, or -1 if this map contains nothing for key. | |
// - remove(key): Remove the mapping for the value in key if it exists. | |
class HashMap { | |
#buffer = [] | |
put(key, value) { | |
let index = 0 | |
while (index in this.#buffer && this.#buffer[index] !== key) index += 2 | |
this.#buffer[index] = key | |
return this.#buffer[index + 1] = value | |
} | |
get(key) { | |
for (let index = 0; this.#buffer[index]; index += 2) | |
if (this.#buffer[index] === key) return this.#buffer[index + 1] | |
return -1 | |
} | |
remove(key) { | |
let doRemove = false | |
for (var index = 0; this.#buffer[index]; index += 2) { | |
if (this.#buffer[index] === key) doRemove = true | |
if (doRemove) { | |
if ((index + 2) in this.#buffer) { | |
this.#buffer[index] = this.#buffer[index + 2] | |
this.#buffer[index + 1] = this.#buffer[index + 3] | |
} | |
else this.#buffer.length = index | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment