JSFiddle - React, Tailwind, and code Playground

by Juan Kristoffer Sanio

HTML

<h1>map,reduce,filter</h1>
Making a combat sequence.<br/>
Alright today I'll be demonstrating the usages of map,reduce and filter in the context of a battle sequence. 

<h2>
Ready
</h2>
Here's the setup, we have a battlefield with 6 units, consisting of both friendlies and hostiles.

<pre>
  const field = [
    { _id: 0, type: 'self' },
    { _id: 1, type: 'ally' },
    { _id: 2, type: 'ally' },
    { _id: 3, type: 'hostile' },
    { _id: 4, type: 'hostile' },
    { _id: 5, type: 'hostile' }
  ];
</pre>

We'll elaborate more on our schema as we progress the development of our game. For now, our game engine is non-existant. The only built-in function is the `attack` function.

<pre>
  const attack = target => target.health--;
</pre>

Yes. Our units now have a health property. Let's assign each with a default of `3` health points. This where I get to introduce our handy `map` function. I want to assume that you, the reader, already knows how to accomplish this using a `for` loop so I can omit that and get straight to showing how it can be done with map function.

<pre>
  const fieldv2 = field.map(units => Object.assign(unit, { health:3 }));
</pre>

Right, we now have a version 2 of our battlefield. Previously all units health value would have been `undefined` which could mean they were either dead or alive, depending on how you want to look at it, but we've changed that and made them all mortal by giving them 3 health points each.

That's the `map` function in action. To put in my own terms, what `map` does is it creates a new array by traversing a given array, takes each value and runs it through the given transformation function.

<p>
Here's another example where, let's say, we crank up the difficulty up by a notch becasuse we're hardcore, and give all hostiles additional health points.
</p>
<pre>
  const fieldv2_hard = fieldv2.map(unit => {
    if (unit.type === 'hostile') unit.health++;
    return unit;
  });
</pre>
<p>
Don't forget the last return statement,...