DEV Community

Cover image for When will I actually use a hashmap?
Elliot Mangini
Elliot Mangini

Posted on

When will I actually use a hashmap?

Concept

"Hashmap" is a fun buzz word.

I ran into a problem where the API I was using supplied comments with a user_id instead of a username. This was an API I made and the right way to fix it might have been to adjust what the main API fetch gave back but I was in a time crunch and was able to create a quick solution using a hashmap

Improperly Formatted Comment

"from user 151"

What I did was at the App level of the React app I did one extra fetch to all Users and created a hashmap to pass down and replace a user ID with a username.

What is a hashmap?

A hashmap is often like a mini dictionary. We can use it to store the outputs of some computationally heavy functions in an object so that the functions don't need to be run multiple times once we know what the outputs are.

In this case we want to create a "dictionary" that relates user_id to username. So it will look something like this.

hashmap = {
    id1: "user 1"
    id2: "user 2"
}
Enter fullscreen mode Exit fullscreen mode

Now wherever we have a user_id in our code we can replace that with

hashmap[user_id]
Enter fullscreen mode Exit fullscreen mode

and get the username itself.

Code

Here's how I implemented it in a React app with a Sinatra & Ruby backend.

Add state for storing hash

const [ userHash, setUserHash ] = useState();
Enter fullscreen mode Exit fullscreen mode

Add a new fetch...

useEffect(() => {
  fetch("http://localhost:9292/userhash")
  .then(resp => resp.json())
  .then(data => {setUserHash(data)});
 }, []);
Enter fullscreen mode Exit fullscreen mode

In Application Controller

get "/userhash" do
  userhash = {}
  User.all.map{|u| userhash[u.id] = u.username }
  userhash.to_json
end
Enter fullscreen mode Exit fullscreen mode

Now our fetch gives us back...

// 20221011094622
// http://localhost:9292/userhash

{
  "50": "DaddyCham",
  "51": "Mullet",
  "52": "Cass",
  "53": "bigsis"
}
Enter fullscreen mode Exit fullscreen mode

🚨 PASS USERHASH TO COMPONENTS IT'LL BE USED 🚨

Now where we had for example...

{comment.user_id}:}
Enter fullscreen mode Exit fullscreen mode

we can replace that with...

{userHash[comment.user_id]}:
Enter fullscreen mode Exit fullscreen mode

And we get our correctly attributed comment:

Fixed Comment

Hope this helps someone out!
-Elliot/Big Sis

Top comments (1)

Collapse
 
elliotmangini profile image
Elliot Mangini

Thanks for sharing your expertise 🙌