lodash

I freakin' love lodash.

In Let Me Take You To Funky Town I showed you how to get started with a Node project. Now I'd like to show you how to add this cool library to that project.

Navigate to your project's directory and type:

npm init  

This is how we add a package.json file. It'll keep some metadata about the project, including what packages it needs installed.

When you type this command, you'll be asked a few questions, just answer them as best you can, it's not too big a deal to get it all correct right at this moment.

Ok, now type:

npm i lodash -save  

npm i is short for npm install. -save tells npm to put dependency information in package.json. Installing a package with npm just means downloading the library into a new directory called node_modules, which... holds all your Node modules! :)

Ok, now let's try this library out. In index.js type the following:

'use strict'  
var _ = require('lodash')

console.log(_.map([1, 3, 4, 5], (x) => 2*x))  

Yes, lodash has it's own versions of map, filter, and reduce, but it has so much more.

I'll be blogging about individual functions in lodash later, but here's a good example. Let's say you have two objects you'd like to merge:

var object_1 = {a: 1, b: 2, c: 7}  
var object_2 = {b: 1, c: 5, d: 4}  

You could just use merge:

_.merge(object_1, object_2)  

Which returns { a: 1, b: 1, c: 5, d: 4 }

But that approach doesn't give you much control. What if you'd like to your keys to have whichever value is greater? (Meaning that, in this example, b would have 2 and c would have 7).

Here's one way to do it:

var merge_objects = (object_1, object_2) =>  
    _(object_1)
        .toPairs()
        .concat(_.toPairs(object_2))
        .reduce((acc, pair) => {
            var current_val = acc[pair[0]]
            if(current_val) {
                acc[pair[0]] =
                    current_val < pair[1]
                        ? pair[1]
                        : current_val
            } else {
                acc[pair[0]] = pair[1]
            }
            return acc
        }, {})

This is an example of chaining. I'll talk about it in greater detail later.

First, merge_objects takes object_1, converts it to an array of key-value pairs (i.e. [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 7 ] ]), does the same thing to object_1 and concatenates them. Next we use reduce to return a new object built using our "use the greatest value" rule.

Pretty sweet eh? There's all kinds of awesome functions in lodash. You can check out the docs here.

Looking for a software developer?