Skip to content

Instantly share code, notes, and snippets.

@tdubs42
Created February 19, 2024 05:58
Show Gist options
  • Save tdubs42/bbb106d673e4add8e27ce3aca189d1ce to your computer and use it in GitHub Desktop.
Save tdubs42/bbb106d673e4add8e27ce3aca189d1ce to your computer and use it in GitHub Desktop.
Hash Map for Dummies - JavaScript

Hash map: A key-value store that uses an array and a hashing function to save and retrieve values. Key: The identifier given to a value for later retrieval. Hash function: A function that takes some input and returns a number. Compression function: A function that transforms its inputs into some smaller range of possible outputs.

Recipe for saving to a hash table:

  • Take the key and plug it into the hash function, getting the hash code.
  • Modulo that hash code by the length of the underlying array, getting an array index.
  • Check if the array at that index is empty, if so, save the value (and the key) there.
  • If the array is full at that index continue to the next possible position depending on your collision strategy.

Recipe for retrieving from a hash table:

  • Take the key and plug it into the hash function, getting the hash code.
  • Modulo that hash code by the length of the underlying array, getting an array index.
  • Check if the array at that index has contents, if so, check the key saved there.
  • If the key matches the one you're looking for, return the value.
  • If the keys don't match, continue to the next position depending on your collision strategy.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment