06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Data Structures and Manipulation<br />

By default, range() populates the array with integers, but with a little trick, you can<br />

populate other data types also:<br />

console.log(_.range(3).map(function () { return 'a' }) );<br />

[ 'a', 'a', 'a' ]<br />

This is a fast and convenient way to create and initialize an array with values.<br />

We frequently do this by traditional loops.<br />

The map() function produces a new array of values by mapping each value in<br />

the list through a transformation function. Consider the following example:<br />

var _ = require('underscore');<br />

console.log(_.map([1, 2, 3], function(num){ return num * 3; }));<br />

//[3,6,9]<br />

The reduce() function reduces a list of values to a single value. The initial state is<br />

passed by the iteratee function and each successive step is returned by the iteratee.<br />

The following example shows the usage:<br />

var _ = require('underscore');<br />

var sum = _.reduce([1, 2, 3], function(memo, num){<br />

console.log(memo,num);return memo + num; }, 0);<br />

console.log(sum);<br />

In this example, the line, console.log(memo,num);, is just to make the idea clear.<br />

The output will be as follows:<br />

0 1<br />

1 2<br />

3 3<br />

6<br />

The final output is a sum of 1+2+3=6. As you can see, two values are passed to the<br />

iteratee function. On the first iteration, we call the iteratee function with two values<br />

(0,1)—the value of the memo is defaulted in the call to the reduce() function and<br />

1 is the first element of the list. In the function, we sum memo and num and return<br />

the intermediate sum, which will be used by the iterate() function as a memo<br />

parameter—eventually, the memo will have the accumulated sum. This concept is<br />

important to understand how the intermediate states are used to calculate eventual<br />

results.<br />

[ 92 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!