DEV Community

Discussion on: Let's Count Some Sheep!

Collapse
 
ekeijl profile image
Edwin • Edited

Instead of counting sheep, how about we reduce them?

function countSheep(array) {
   return array.reduce((sum, bool) => sum + bool);
}

What's going on here? Where did the sum come from?? Adding the a boolean to a sum??? Are you nuts?!

Ok let's go step by step.

  • Reduce is an array prototype function that executes a reducer function for each of the items in the array and returns a single value.
const reducer = (accumulator, currentValue) => accumulator + currentValue;
  • The reducer function takes 2 arguments:
    • A so called accumulator, in our case it's the sum. The value that you return in the reducer function becomes the accumulator for the next iteration.
    • The value of the current iteration, our boolean!
  • We want to count total amount of times we encounter true.
    • In other words: the sum of all booleans with value true.
    • In other other words, if the value of our current iteration is true, we want to increment the sum by 1.
    • In pseudo code: sum = sum + (true ? 1 : 0).
  • So what about sum + boolean???
    • We need to use a smart little trick: if you convert a boolean to a number, then true will become 1 and false becomes 0. So Number(true) === 1.
    • If we use the addition operator +, JavaScript will automatically convert values to numbers for you!

Now, you may have noticed that we never declare sum anywhere. We never tell the reduce function to start counting at 0. Next to the reducer function, Array.reduce() can take a second parameter, which is the initial value for the accumulator. If we do not pass an initial value, it will just take the first value of our array.

There you have it!

We can just add the boolean to our sum, and it will add 1 if it is true or 0 for false, exactly what we want.

Collapse
 
michellekaplan7 profile image
Michelle Kaplan

That's so cool Edwin! Reduce sounds like a very interesting prototype that I'm going to look into more!