Lodash is a modern JavaScript utility library delivering modularity, performance & extras.
You have probably used Lodash in one of your projects.
Wouldn’t it be great if every javascript developer could experiment Lodash in her browser without needing to install anything or to create a JsFiddle?
Today, this dream comes true. In this blog post, you can play with Lodash functions. Experiment the edge cases of the API. Compose a short gist and check if it works as expected….
The interactive code snippets are powered by Klipse.
Go ahead! Enjoy! Reconnect with your inner child!
My personal fun session with Lodash, was to write a function that receives an array and calculate the frequency of its elements.
First try was to use countBy
:
_.countBy([1,2,3])
Now, we need to divide each value by the length of the array. For that we need to write a function that receives an object and maps its values:
function mapVals(obj, f) {
return _.zipObject(_.keys(obj), _.map(_.values(obj), f))
}
Let’s check our code:
mapVals({a: 1, b: 2, c:3}, x => x*x)
Now, we have all the lego pieces for writing our frequencies
function:
function frequencies(arr) {
return mapVals(_.countBy(arr), occurences => occurences/arr.length);
}
It seems to work:
frequencies(["aa", "aa", "bb"])
Now it’s your turn to play.
In case you don’t remember how a specific function works, Lodash documentation is just here.
Are you proud of the function that you created?
Feel free to share it in the comments below…