When you need a break from ‘reduce’

Let’s say that you moved from for-each style of programming to more functional one with map, reduce and filter and writing foreach loop looks already strange for you. Now you have a task that that usually Array.reduce does — aggregation but you need to break in the middle.

Es6 array reduce function does not provide a way to stop execution and it will iterate over all collection elements. To solve this use case Lodash transform function can be used. It have exactly the same behaviour as Array.reduce but it allows you to stop execution by returning false instead of returning accumulator as reduce does.

Here is an example. There is a very expensive function that calculates a person name. The task is for a collection of people to get the first not null name. Lodash’s transform will allow you to use ‘reduce’ style but break.

let {name:myName} = _.transform(peoples, (acc, people) => {
acc['name'] = longCalculateExpensive(people);
if (acc['name']) {
return false;
}, {name: ''});
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.