ShakaCode | ShakaCode Blog | Rails On Maui Blog | Rails | ReactJs | JavaScript | Webpack | Productivity |

Lodash Tips and Tricks


#1

Lodash is an incredibly useful JS library. I’d go as far as to say that it’s mandatory for any big projects.

I highly recommend this new article: Lodash: 10 Javascript Utility Functions That You Should Probably Stop Rewriting.

But don’t just read the article, experiment with the syntax in https://jsbin.com

I created an example here of a bit of syntax that’s not working, at least not with the version of lodash provided by jsbin: https://jsbin.com/mapala/edit?js,console,output

Here’s the docs: http://devdocs.io/lodash/index#map

I love the quick searching on that page.

I ran into one issues with the examples. It’s possible that the version of lodash on the jsbin website is different.

var ownerArr = [{
    "owner": "Colin",
    "pets": [{"name":"dog1"}, {"name": "dog2"}]
}, {
    "owner": "John",
    "pets": [{"name":"dog3"}, {"name": "dog4"}]
}];

// Array's map method.
ownerArr.map(function(owner){
   return owner.pets[0].name;
});

// Lodash
// This breaks in 3.0, but works in 3.10
_.map(ownerArr, 'pets[0].name');

// This works
_.map(ownerArr, 'pets');

Update:

Check out :

and this codepen which uses 3.10 of lodash!


#2

ES6

  Highcharts.charts
    .filter( c => c && isVisible(c.container))
    .forEach(c => console.log(c));

Lodash

When using Lodash chaining, you need to be careful to call value() at the end!

https://lodash.com/docs#_

Creates a lodash object which wraps value to enable implicit chaining. Methods that operate on and return arrays, collections, and functions can be chained together. Methods that retrieve a single value or may return a primitive value will automatically end the chain returning the unwrapped value. Explicit chaining may be enabled using _.chain. The execution of chained methods is lazy, that is, execution is deferred until _#value is implicitly or explicitly called.

Lazy evaluation allows several methods to support shortcut fusion. Shortcut fusion is an optimization strategy which merge iteratee calls; this can help to avoid the creation of intermediate data structures and greatly reduce the number of iteratee executions.

For example, it would be easy to forget the .value(), when comparing to the equivalent ES6 version.

  _(Highcharts.charts)
    .filter( c => c)
    .filter( c => isVisible(c.container))
    .forEach(c => console.log(c))
    .value(); // Needed to tell lodash to actually run the code

#3

I’m currently taking a course by the technical lead at Netflix that is on ReactiveX. It allows you to use this style of method chaining even for for asynchronous streams of data, which is super cool. The exercises are public for everyone, check it out!: http://reactivex.io/learnrx/