6 Staying immutable in a mutable language

 
Image

In this chapter

  • Apply a copy-on-write discipline to ensure that data is not changed.
  • Develop copy-on-write operations for arrays and objects.
  • Make copy-on-write work well for deeply nested data.

We’ve been talking about immutability, and we’ve even implemented it in some places. In this chapter, we’re going to dive deep. We’ll learn to make immutable versions of all of the common JavaScript array and object operations we’re used to using.

Can immutability be applied everywhere?

We’ve already implemented some shopping cart operations using a copy-on-write discipline. Remember: That means we made a copy, modified the copy, then returned the copy. But there are a number of shopping cart operations we haven’t done yet. Here is a list of the operations we need or might need for the shopping cart and for shopping cart items:

Image Vocab time

We say data is nested when there are data structures within data structures, like an array full of objects. The objects are nested in the array. Think of nesting as in Russian nesting dolls—dolls within dolls within dolls.

We say data is deeply nested when the nesting goes on for a while. It’s a relative term, but an example might be objects within objects within arrays within objects within objects… The nesting can go on a long time.

Shopping cart operations

Categorizing operations into reads, writes, or both

The three steps of the copy-on-write discipline

Converting a write to a read with copy-on-write

Complete diff from mutating to copy-on-write

These copy-on-write operations are generalizable

JavaScript arrays at a glance

What to do if an operation is a read and a write

Splitting a function that does a read and write

Returning two values from one function

Reads to immutable data structures are calculations

Applications have state that changes over time

Immutable data structures are fast enough

Copy-on-write operations on objects

JavaScript objects at a glance

Converting nested writes to reads

What gets copied?

sitemap