Problem
const mockAPIData = {
  items: [
    { id: 1, price: 100 },
    { id: 2, price: 200 }
  ]
};

class DataCache {
  constructor() {
    this.cache = new Map();
  }

  getData(key) {
    if (!this.cache.has(key)) {
      this.cache.set(key, mockAPIData);
    }
    return this.cache.get(key);
  }

  calculateTotal(data) {
    data.items.forEach(item => {
      item.price = item.price * 1.2;
    });
    return data;
  }
}

const cache = new DataCache();
const data = cache.getData('products');
const withTax = cache.calculateTotal(data);
console.log('Before tax calculation:', data.items[0].price);
console.log('With tax:', withTax.items[0].price);
Solution

The calculateTotal method mutates the reference to the original data. This means that the original data is modified in place, which can lead to unexpected behavior. To fix this, you should create a new object in the calculateTotal method and return that instead of modifying the original data. Here’s the corrected code:

const mockAPIData = {
  items: [
    { id: 1, price: 100 },
    { id: 2, price: 200 }
  ]
};

class DataCache {
  constructor() {
    this.cache = new Map();
  }

  getData(key) {
    if (!this.cache.has(key)) {
      this.cache.set(key, mockAPIData);
    }
    return this.cache.get(key);
  }

  calculateTotal(data) {
    const newData = {
      items: data.items.map(item => ({
        ...item,
        price: item.price * 1.2
      }))
    };
    return newData;
  }
}

const cache = new DataCache();
const data = cache.getData('products');
const withTax = cache.calculateTotal(data);
console.log('Before tax calculation:', data.items[0].price);
console.log('With tax:', withTax.items[0].price);