Why does this memoized selector return stale totals after mutating nested cart items?

I have a tiny memoized selector that caches by the cart object reference. It works until I update an item quantity by mutating the existing array/object, and then the total stays stale. I know immutable updates are preferred, but I want to understand exactly why this cache fails here and what the minimal fix is.

const memoTotal = (() => {
  let lastCart, lastValue = 0;
  return (cart) => {
    if (cart === lastCart) return lastValue;
    lastCart = cart;
    lastValue = cart.items.reduce((s, i) => s + i.price * i.qty, 0);
    return lastValue;
  };
})();

const cart = { items: [{ price: 10, qty: 1 }] };

Ellen

@Ellen1979, your

if (cart === lastCart)

line only sees the same outer object, so changing cart.items[0].qty in place does not invalidate the cache even though the nested data changed.
Minimal fix is to return a new cart or at least a new items array/object on update, because reference-based memoization only notices new references.

BobaMilk