2022-12-12 Debugging chained operations in Lodash

I use Lodash in some of my projects. One of the nice features of Lodash is the chaining concept. If you have an object (often an array) which you want to transform usign a series of operations like map, filter etc., you can say e.g.

_(array)
    .filter(function1)
    .map(function2)
    .sampleSize(size)
    .orderBy(field)
    .value()

to first filter array, then map it (using a function or the iteratee shorthand), then draw random size elements, and finally sort them by field.

Now this is great – if it works. But what if it doesn’t and the result is completely unexpected? It would be nice if you were able to see the intermediate results of the chained operations without, so to speak, breaking the chain…

It turns out you can! Lodash has the _.tap function which accepts two arguments. The former one is a value (which is also what _.tap returns). The latter one is a function which _.tap evaluates on the value. Of course, the point is that the functon given has some side effects – it can either modify the value or – for example – print it out. And _.tap is chainable, so you can say this:

_(array)
    .filter(function1)
    .map(function2)
    .tap(console.log)
    .sampleSize(size)
    .orderBy(field)
    .value()

and see the array after mapping but before drawing random size elements on the console. Very handy!

CategoryEnglish, CategoryBlog, CategoryJavaScript