pccse
pccse

Reputation: 77

_.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();

Upvotes: 6

Views: 5580

Answers (2)

Neil Ostrove
Neil Ostrove

Reputation: 43

This works and is (IMHO) a little clearer.

var sum = _(_.range(1000)).chain()
          .filter(function (x) { return (x % 3 === 0  ||  x % 5 === 0) })
          .reduce(function (sum, x) { return sum + x }, 0)
          .value();    /* try chaining range() and reduce() */

I'm assuming it's OK to solve JavaScript koans here?

Upvotes: 0

Mariano Desanze
Mariano Desanze

Reputation: 8163

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.

Upvotes: 8

Related Questions