Using Belt.Map.update
Back in our discussion of Belt.Map, we updated a map of the color counts by using Belt.Map.getWithDefault and Belt.Map.set. While this works, you may find it more convenient to use Belt.Map.update. This function takes as its parameters the map to be updated, a key, and a function. It works as follows:
-
Attempt to get the value for the given key using Belt.Map.get. This returns an option. If the value is None, the key isn’t in the map, so return the map unchanged.
-
Otherwise, apply the function to the value. If the function returns None, return a map with the key and value removed.
-
If the function returns Some(value), then return an updated map where the value for the given key is value.
Let’s look at a concrete example: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access