API reference › @evolu/common › Object › shareStructure

function shareStructure<T>(
  previous: T,
  next: T,
  itemToKey?: (item: unknown) => unknown,
): T;

Defined in: packages/common/src/Object.ts:412

Returns next with every part deep-equal to the same part of previous replaced by that part, or previous itself when the two are deep-equal.

It keeps the identity of data that arrives as a new copy, such as a structured clone posted between workers, so unchanged parts can be compared with ===, and a UI updates only what changed. Plain objects, arrays, and Uint8Arrays are compared by their contents, and any other value by identity. The contents of a plain object are the properties an object spread copies. A changed object or array is returned as a new ordinary one. It walks the data as a tree, so a part referenced from several places is compared at each place, and a part that a cycle leads back to is returned as it is in next.

An array item is compared with the previous item at its index, so removing or inserting an item compares every item after it with a different one. When itemToKey returns a key for an item, such as its ID, the item is compared with the previous item of the same key instead. Keys are compared as Map keys are, so each should be unique in its array; an item whose key several previous items share is compared with the last of them.

Example

import {
  assertNotSame,
  assertSame,
  isPlainObject,
  shareStructure,
} from "@evolu/common";

const previous = {
  user: { name: "Alice" },
  todos: [{ title: "Buy milk" }],
};

// An equal copy gives the previous value back.
assertSame(shareStructure(previous, structuredClone(previous)), previous);

// A change keeps every unchanged part.
const next = shareStructure(previous, {
  user: { name: "Alice" },
  todos: [{ title: "Buy bread" }],
});
assertNotSame(next, previous);
assertSame(next.user, previous.user);
assertNotSame(next.todos, previous.todos);

// A key compares each todo with the previous todo of the same ID.
const todos = [
  { id: 1, title: "Buy milk" },
  { id: 2, title: "Walk the dog" },
];
const remaining = shareStructure(
  todos,
  [{ id: 2, title: "Walk the dog" }],
  (todo) => (isPlainObject(todo) ? todo.id : undefined),
);
assertSame(remaining[0], todos[1]);