liveBook · Manning

Copy-on-write

As explained in Grokking Simplicity

A data-management technique that creates a copy before modifying data so the original remains unchanged.

Copy-on-write is a data-management technique for preserving immutability in a mutable language. Instead of changing the original value, make a copy, modify the copy, and return it. section 6.20 section 6.3

Apply the discipline in three steps:

Adding an element without changing the original

function add_element_last(array, elem) { var new_array = array.slice(); new_array.push(elem); return new_array; } The original array remains unchanged, while the returned array contains the new element. The same pattern can support array updates, object updates, and reusable wrappers such as withArrayCopy(). section 6.3 section 11.3

function arraySet(array, idx, value) {
    return withArrayCopy(array, function(copy) {
        copy[idx] = value;
    });
}
 
function withArrayCopy(array, modify) { #1
    var copy = array.slice();
    modify(copy);
    return copy;
}

A callback-based wrapper isolates the copy-and-return parts of the discipline while allowing the modification to vary. section 11.3

How Grokking Simplicity covers it

How deep it goes
Explains three procedural steps, read-write separation, shallow copies, nested updates, and reusable callback wrappers.
Examples
Uses shopping carts, mailing lists, array methods, object updates, nested prices, and callback-based array utilities.
What it assumes
Assumes basic JavaScript arrays and objects while teaching immutability, reads, writes, and copy-on-write from first principles.
What you can do after
Build it from scratch by converting mutating JavaScript operations into immutable functions that return updated values.
How it connects
Connects immutability with functional programming, defensive copying, reads, writes, arrays, objects, and nested data structures.

Also explained in

Compare how 5 books explain copy-on-write →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.