Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore reduce, about memo

According the documentation underscore-reduce I should pass three parameters.

For example:

var m = _.reduce([1,2,3], function (memo, num) {return (num * 2) +memo }, 0);
m; // 12 as expected

If I try to pass just the first two parameters I get a different value. Why?

var m = _.reduce([1,2,3], function (memo, num) {return (num * 2) +memo });
m; // 11 ..why?
like image 786
Lorraine Bernard Avatar asked Aug 01 '12 13:08

Lorraine Bernard


1 Answers

With only two parameters passed into reduce, it will use the first and second array items as arguments to the first function call.

function addDouble(memo, num) {return (num * 2) +memo }

[1,2,3].reduce(addDouble, 0)
// is equivalent to
addDouble(addDouble(addDouble(0, 1), 2), 3)

[1,2,3].reduce(addDouble)
// is equivalent to
addDouble(addDouble(1, 2), 3)

Usually you will pass the start value, but many operations have the same result when starting without their identity element. For example:

function add(a, b) { return a+b; }
function double(a) { return 2*a; }

[1,2,3].map(double).reduce(add) == [1,2,3].map(double).reduce(add, 0)

See also the docs for native reduce().

like image 121
Bergi Avatar answered Oct 21 '22 21:10

Bergi