Third Person Shooter Example
Imagine you are building a third-person shooter game, and you have an array of objects that represent the player's weapons. Each weapon object has the following properties:
name
: the name of the weapondamage
: the base damage dealt by the weaponaccuracy
: a value between 0 and 1 representing the weapon's accuracyammo
: the number of rounds left in the weapon's magazine
You can use the Array.prototype.reduce()
method to calculate the total damage dealt by all of the player's weapons that have ammo remaining.
Here is an example of how you could do this:
In this example, the reduce()
function is called on the weapons
array with two arguments: a callback function and an initial accumulator value of 0
. The callback function has two arguments: accumulator
and weapon
.
On each iteration, the callback function checks if the current weapon
has ammo remaining (weapon.ammo > 0
). If it does, the callback function adds the damage
property of the weapon
object to the accumulator and returns the new value. If the weapon
has no ammo remaining, the callback function simply returns the current value of the accumulator without modifying it. This process continues until all elements in the array have been processed, and the final value of accumulator
is returned as the total damage dealt by all weapons with ammo remaining.
Last updated