domenic / count-to-6

An intro to some ES6 features via a set of self-guided workshops.
Other
326 stars 76 forks source link

Hand with ARROW FUNCTIONS, Part 1 #32

Closed rickschmoo closed 8 years ago

rickschmoo commented 8 years ago

Can someone give me a hand understanding the solution for ARROW FUNCTIONS, Part 1 ?

I'm fine as far as the reduce ...

var result = inputs.map(s => s[0])
                       .reduce((soFar, s) => soFar + s);

The output of the map is of the form:

[ 'J', 'i', 'f', 'a', 's', 'N', 'i', 'f' ]

and the reduce is doing a recursive concatenation. What I'm confused about is what are the initial values of soFar and s?

Thanks!

vishant-dhandha commented 8 years ago

Syntax for reduce Function is like this...

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
});

Reduce is an iterative method.. so each time previousValue , currentValue & index will be change.. In this scenario , 1st iteration: previousValue = 0 & currentValue = 1 2nd iteration: previousValue = 1 & currentValue = 2 3rd iteration: previousValue = 3 & currentValue = 3

In your code you have used reduce method like this..

[ 'J', 'i', 'f', 'a', 's', 'N', 'i', 'f' ].reduce(function(previousValue, currentValue) {
  return previousValue + currentValue;
});

So from this , 1st iteration: soFar = 'J' & s = 'i' 2nd iteration: soFar = 'Ji' & s = 'f' 3rd iteration: soFar = 'Jif' & s = 'a'

You can find Help about reduce function here

rickschmoo commented 8 years ago

Thanks @vishant-dhandha - thats tremendously useful. Cheers!