A Map to Success: Functors in Javascript

I wanted to take some time to talk about the humble map function. If you have ever used libraries like underscore, lodash, or ramda, you are sure to encounter more than a few curious functions. The unassuming map function is a good starting point on our journey to functional nirvana.

Making a map

Taking a step back, what is map? Just like a paper map, the function map is a guide to get from one place to another.

  1. We apply a transformation to each item in the list

Other Data Types

Now forget about arrays and remember that map is just a means to get from one place to another. We do this by giving map a transformation function and some data to work on. How could we implement this on other data types?

Linked Lists

Keeping things array like, we will start by using linked lists.

Trees

Are you starting to see the beauty of map? One more example perhaps! Thus far we have worked with array like structures, what about non arrays, like trees? The principle behind map stays the same, we have a function that takes some data on a journey from one value to another. It does this by running a transformation over its internals. In a tree’s case, we want to go over each node in the tree and apply our transformation to it.

Finding Patterns

One of the simple pleasures of programming is finding patterns and making them into reusable snippets. What patterns have we found with map?

And What About Functors?

Now you may ask “Kevin, you promised me Functors and you never once mentioned them!” In response, I simply raise my eyebrows and exclaim “We have been talking about Functors all along!”

  1. SomeType.map(f1(x)).map(f2(x)) == SomeType.map(f2(f1(x))), or in other words Composition. We can flatten multiple map calls by chaining their transformations together and vice versa.

Conclusion

When getting into functional programming, we are bombarded by intimidating words and principles. Functors, Monoids, Monads, Comonads, Endofunctors, the list goes on. At the core of it, the principles are quite simple; we just need to get beyond the names and see their use cases.

WebApps Engineer at Willowtree

WebApps Engineer at Willowtree