The Advent of Code in Elixir continues to be a humbling experience year after year. One of my weaknesses in programming puzzles and, in general, is a lack of intuition on which common collection operations to use. Or, to be more precise, since I don't know them intimately, I don't know when to apply them in code. It is way too often I get feedback on a code review on why do you do this thing with a plain map or reduce while you could use this and that helper function. Often, one can replace a custom function with a more expressive composition of well-known "stock" functions.
I think a recap is in order. I enumerate in this post the most useful ones for me - or at least those I get the most feedback from. These are indeed useful even in the basic CRUD app!
I took the names from Scala and Elixir standard libraries and checked that functions with similar names exist in Lodash and Ramda JS external libraries
Chunk/Group/Split/Partition
Make a list of lists based on a filter or index. Useful, for example, in UI code where you want to show different UI components based on the shape of the data.
Union
Combine two lists with duplicates removed. Useful for funnels. Or combining work in a task queue.
Intersection
Combine two lists with common elements, discard others.
Difference
Returns a list C which contains elements in list A not in list B.
Not too long ago, I used it in the following scenario
- Given a set of elements
- Send the set to some evil function that wants to destroy one or more of the elements
- The evil function returns a new set of elements with some removed
- Use a difference function to collect the removed elements.
- Use their IDs to remove them from a DB.
Similar case:
- List of elements A, B, and C cached locally
- Call an API to get the latest state
- It responds with elements A, E
- Difference one-liner returns the new state
Zip
Form pairs of two lists. Useful for example in pivoting arrays. A classic in the Advent of Code puzzles.
Once again, I have fallen behind badly 😅 |
Comments
Post a Comment