Skip to content
Advertisement

_.chain – underscore JS

This code works fine

var arr = _.range(1,1000);
var parse = _.filter(arr, function(num) {return num%3===0 || num%5===0});
var sum = _.reduce(parse, function(memo, num){ return memo + num; }, 0) //233168

Is it possible to use the _.chain() function to clean this code up? I’ve tried to code below, but it gives a Type error.

var arr = _.range(1,1000);
var sum = _.chain(arr)
        .filter(arr, function(num) {return num%3===0 || num%5===0})
        .reduce(arr, function(memo, num){ return memo + num; }, 0)
        .value();

Advertisement

Answer

You just need to remove the first argument (arr) from each of the functions you have inside the _.chain() and _.value() (as they are now gather from the chain):

var arr = _.range(1,1000);
var sum = _.chain(arr)
    .filter(function(num) {return num%3===0 || num%5===0})
    .reduce(function(memo, num){ return memo + num; }, 0)
    .value();

And you could also do it a little more concise, by splitting the range arguments (i.e. 1 and 1000) between the chain function and the range function:

var sum = _.chain(1).range(1000)
    .filter(function(num) {return num%3===0 || num%5===0})
    .reduce(function(memo, num){ return memo + num; }, 0)
    .value();

It works, but I’m not sure if this last one is a good idea in terms of code readability.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement