One Pager Cheat Sheet
- You can implement a
Hashmapclass from scratch, with thegetandsetmethods for retrieving and storingkeyandvaluepairs, and a hashing function for converting strings to integers, to enableO(1)lookups. - We are creating a
Hashmapdata structurebased off a legacyHashtable, taking advantage of a hash function to mapkeystobucketsand store our data in the corresponding index of an array. - The
keyprovided toset()is used to compute a location in thehashStr()function, and an array is needed for the actual value storage. - The slots of a hash table are typically stored in an array whose
indicesrefer to the computed location given by the hash function, and whose buckets refer to thedata structurein which thekey-valuepairs are stored for efficient insertion and retrieval. - Creating a
classwith a storage array as the bare minimum is a goodinitializationstep. - We will
hashStrto determine the appropriate index to store the value inthis._storage, and handle any possiblecollisionsusing additional data structures. - Hash tables can use a
linked liststructure to store multiple values at the same index to prevent collisions. - We can
implement the set methodby converting thekeyto anindexinthis._storageand setting thevalueusing an array to primitively solve for the collision problem. - Both
getandsetmethods take akeyas an argument and use thehashStrmethod to find the appropriate index in a data structure;getreturns the value located at the index, whilesetstores akey-valuepair at the indexed location. - When using these methods, we should always check to see if a key exists and handle any cases where it doesn't by returning
undefinedorNone. - The
hash mapdata structure grows linearly withO(n)space complexity, withO(1)constant get/set complexity in most cases, andO(n)linear get/set complexity in the worst case.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx85
}var assert = require("assert");​class Hashmap { constructor() { this._storage = []; }​ hashStr(str) { let finalHash = 0; for (let i = 0; i < str.length; i++) { const charCode = str.charCodeAt(i); finalHash += charCode; } return finalHash; }​ set(key, val) { let idx = this.hashStr(key);​ if (!this._storage[idx]) { this._storage[idx] = []; }​ this._storage[idx].push([key, val]); }​ get(key) { let idx = this.hashStr(key);​ if (!this._storage[idx]) { return undefined; }OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.

