Racing Game Example

Imagine you are building a racing game where the player can customize their car with different parts. The car is represented as an object with the following properties:

  • engine: the type of engine the car has

  • tires: the type of tires the car has

  • suspension: the type of suspension the car has

You can use immutable array operations to create a new car object each time the player upgrades a part, without modifying the original car object. Here is an example of how you could do this:

const initialCar = {
  engine: 'V6',
  tires: 'all-season',
  suspension: 'standard'
};

function upgradePart(car, part, value) {
  return {
    ...car,
    [part]: value
  };
}

let currentCar = initialCar;

// Upgrade the engine
currentCar = upgradePart(currentCar, 'engine', 'V8');

console.log(initialCar.engine); // 'V6'
console.log(currentCar.engine); // 'V8'

In this example, the upgradePart() function takes the current car object, the name of the part to upgrade, and the new value for that part. It creates a new car object using the spread operator, and then updates the specified part using computed property names. The currentCar variable is updated to the new car object, and the original car object is not modified.

Using immutable array operations in this way allows you to keep track of the player's progress and revert to previous states if necessary, without having to worry about modifying the original car object. It also makes it easier to debug any issues that may arise, because the car's state is not changed unexpectedly.

Last updated