Hash Tables for Speed
While hash tables are a perfect fit for paired data, they can also be used to make your code faster—even if your data doesn’t exist as pairs. And this is where things get exciting.
Here’s a simple array:
| const array = [61, 30, 91, 11, 54, 38, 72]; |
If you want to search for a number in this array, how many steps would it take?
Because the array is unordered, you’d have to perform a linear search, which would take N steps—you learned this back at the beginning of the book.
However, what would happen if we ran some code that would convert these numbers into a hash table that looked like this?
| const hashTable = {61: true, 30: true, 91: true, |
| 11: true, 54: true, 38: true, 72: true} |
Here, we’ve stored each ...
Get A Common-Sense Guide to Data Structures and Algorithms in JavaScript, Volume 1 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.