# Indexes and sets

> Read when a value follows a collection a row at a time. Keep a set of keys, the keys of each group, and a sum per group, with collections, boxes, and onRowChange.

## Example

Each structure on this page takes a few lines over the calls on
[Collections](../state/collections.md); Pinna has no call for any of them.
`onRowChange` keeps a structure in step with a collection a row at a time.
The samples share one collection of orders, with amounts in whole cents.

```ts
import { collection, createRealm } from "@frondruntime/pinna";

const realm = createRealm();

interface Order {
  readonly id: string;
  readonly customer: string;
  /** Whole cents, so a sum kept by adding and subtracting stays exact. */
  readonly cents: number;
}

const $orders = collection(realm, {
  keyOf: (order: Order) => order.id,
  equals: (previous, next) => previous.customer === next.customer && previous.cents === next.cents,
});
```

A set of keys is a collection keyed by the key itself. `read.row` tracks
one key, so a row that asks whether it is selected reruns only when its own
key joins or leaves the set. An array in a box reruns every such reader on
each change, and each one scans the array.

```ts
import { collection, computedFunction, update } from "@frondruntime/pinna";

// A set of order ids: a collection keyed by the id itself.
const $selected = collection(realm, { keyOf: (id: string) => id });

const toggleSelected = (id: string) => {
  update(realm, (read, write) => {
    if (read.row($selected, id) === undefined) {
      write.upsert($selected, id);
    } else {
      write.remove($selected, id);
    }
  });
};

// Tracks one id: selecting another order reruns nothing here.
const isSelected = computedFunction(
  realm,
  (read, id: string) => read.row($selected, id) !== undefined,
);
```

A value per group, such as its keys or its sum, is one box per group, made
on the first ask. A map of groups in one box copies every group on each
change and reruns every reader of every group.

```ts
import { type Box, box, type Realm } from "@frondruntime/pinna";

// One box per key, made on the first ask. The map holds boxes, never values,
// so a write that fails puts back what the boxes hold and leaves at most an
// empty box behind.
const boxPerKey = <Key, Value>(realm: Realm, initial: Value) => {
  const boxes = new Map<Key, Box<Value>>();
  return (key: Key): Box<Value> => {
    let $value = boxes.get(key);
    if ($value === undefined) {
      $value = box(realm, initial);
      boxes.set(key, $value);
    }
    return $value;
  };
};
```

The ids of each customer's orders. `onRowChange` reports a row `before` and
`after` the write, so an order that moves to another customer leaves one
group and joins the other in the same report.

```ts
import { onRowChange } from "@frondruntime/pinna";

// The ids of each customer's orders. A write to one customer's orders reruns
// the readers of that customer alone.
const ordersOf = boxPerKey<string, ReadonlyArray<string>>(realm, []);

const stopOrdersOf = onRowChange($orders, ({ key, before, after }, read, write) => {
  if (before?.customer === after?.customer) {
    return; // a new amount under the same customer moves no id
  }
  if (before !== undefined) {
    const $ids = ordersOf(before.customer);
    write(
      $ids,
      read($ids).filter((id) => id !== key),
    );
  }
  if (after !== undefined) {
    const $ids = ordersOf(after.customer);
    write($ids, [...read($ids), key]);
  }
});
```

A sum per customer subtracts the row `before` and adds the row `after`: two
writes per change, however many orders the customer has.

```ts
import { onRowChange } from "@frondruntime/pinna";

// The sum of each customer's orders, in cents.
const totalOf = boxPerKey<string, number>(realm, 0);

const stopTotalOf = onRowChange($orders, ({ before, after }, read, write) => {
  if (before !== undefined) {
    const $total = totalOf(before.customer);
    write($total, read($total) - before.cents);
  }
  if (after !== undefined) {
    const $total = totalOf(after.customer);
    write($total, read($total) + after.cents);
  }
});
```

A graph is a collection of edges with two such indexes, one by source and
one by target. A walk over it, such as every key reachable from one key, is
a function that reads them, run in a `computed` or an update, and reruns in
full on each change it reads. Rows kept in sorted order are on
[Collections](../state/collections.md#sorted-rows).

## Rules

- Keep what a listener builds in boxes and collections, so a failed write
  puts it back with the row ([Collections](../state/collections.md)).
- Skip a report that leaves a row's group as it was. Removing the key and
  adding it again moves it to the end of its group and reruns that group's
  readers for nothing.
- Keep amounts as integers. Each floating-point add and subtract rounds, so
  a sum kept that way drifts from the sum of its rows.
- A change copies the group it writes, as a collection copies its key order
  when a key is added or removed.
- A `computed` over `rows` derives the same values with no listener, and
  reruns over every row on each change. It fits a collection that is small
  or rarely written.

## See also

- [Collections](../state/collections.md): `onRowChange`, `read.row`, what each write reports, and sorted rows.
- [Updates](../state/updates.md): the update a listener runs in, and what a failed one puts back.
- [Collection fields](../effect/collections.md): a collection as a field of a `SchemaModel`.
