# Equality and hashing

> Read when a write, a refetch, or a reconcile keeps or replaces a value. Know what each box, collection, and reconcile compares with by default, why two decodes of a model with a box are not equal unless the class defines its own Equal, what Effect's Equal.equals and HashSet see, and how a class defines its own Equal and Hash.

Pinna compares a value written over the one held. When the two are equal,
the held value stays, and nothing that read it reruns. What counts as equal
depends on what holds the value. The Effect pages are for applications that
already use Effect: see [Schema-checked boxes](./boxes.md).

## Example

A `schemaBox` compares as `Schema.toEquivalence` of its schema does. An
equal write keeps the object the box holds.

```ts
import { createRealm, schemaBox, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";

const realm = createRealm();

const Reading = Schema.Struct({ at: Schema.Date, value: Schema.Number });
type Reading = typeof Reading.Type;

const $reading = schemaBox(realm, Reading, { at: new Date(0), value: 1 });

const record = (reading: Reading) => {
  update(realm, (_read, write) => {
    // A Date compares by its time: an equal reading keeps the object
    // the box holds, and nobody reruns.
    write($reading, reading);
  });
};
```

A `SchemaModel` without its own Equal compares its boxes and its realm by
identity, so two decodes of the same JSON are not equal when the class has a
`$` field.

```ts
import { BoxField, decode, SchemaModel } from "@frondruntime/pinna-effect";
import { Schema } from "effect";

class Position extends SchemaModel<Position>("Position")({
  id: Schema.String,
  $size: BoxField(Schema.Number),
}) {}

const samePosition = Schema.toEquivalence(Position);
const first = decode(realm, Position)({ id: "a", size: 1 });
const again = decode(realm, Position)({ id: "a", size: 1 });

// false: each decode makes its own $size box, and boxes compare by identity.
const positionsEqual = samePosition(first, again);
```

A refetch through `write.replaceAll` keeps each plain row that did not
change.

```ts
import { CollectionField, decode, SchemaModel, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";

// No `$` field, so a plain Schema.Class.
class Quote extends Schema.Class<Quote>("Quote")({
  symbol: Schema.String,
  price: Schema.Number,
}) {}

class Market extends SchemaModel<Market>("Market")({
  $quotes: CollectionField(Quote, { keyOf: (quote) => quote.symbol }),
}) {}

const market = decode(realm, Market)({ quotes: [] });

const receiveQuotes = (json: unknown) => {
  const quotes = decode(realm, Schema.Array(Quote))(json);
  update(realm, (_read, write) => {
    // A quote equal under Quote's schema is kept, and what read its row does not rerun.
    write.replaceAll(market.$quotes, quotes);
  });
};
```

A refetched `SchemaModel` row is merged into the held one, so a component
that reads the row reruns only when a plain field changes, and one that
reads `$size` reruns when the size does.

```ts
import { decode, reconcileSchema, schemaBox, update } from "@frondruntime/pinna-effect";
import { Schema } from "effect";

const $positions = schemaBox(realm, Schema.Array(Position), []);

const receivePositions = (json: unknown) => {
  const fresh = decode(realm, Schema.Array(Position))(json);
  update(realm, (read, write) => {
    // A held id keeps its Position, and the new size goes into its $size box.
    write(
      $positions,
      reconcileSchema(read($positions), fresh, { keyOf: (position) => position.id }),
    );
  });
};
```

A `SchemaModel` that defines `[Equal.symbol]` decides its own equality. A
refetched rate under a held pair is merged, and its box takes the new bid.

```ts
import {
  BoxField,
  decode,
  reconcileSchema,
  SchemaModel,
  schemaBox,
  update,
} from "@frondruntime/pinna-effect";
import { Equal, Hash, Schema } from "effect";

class Rate extends SchemaModel<Rate>("Rate")({
  pair: Schema.String,
  $bid: BoxField(Schema.Number),
}) {
  // One rate per pair. Plain fields only: Effect caches what Equal.equals answers.
  [Equal.symbol](that: unknown): boolean {
    return that instanceof Rate && that.realm === this.realm && this.pair === that.pair;
  }

  [Hash.symbol](): number {
    return Hash.string(this.pair);
  }
}

const $rates = schemaBox(realm, Schema.Array(Rate), []);

const receiveRates = (json: unknown) => {
  const fresh = decode(realm, Schema.Array(Rate))(json);
  update(realm, (read, write) => {
    // A pair already held keeps its rate, and the new bid goes into that rate's box.
    write($rates, reconcileSchema(read($rates), fresh, { keyOf: (rate) => rate.pair }));
  });
};
```

`{ equals }` replaces the default of any box.

```ts
import { schemaBox } from "@frondruntime/pinna-effect";
import { Schema } from "effect";

const Row = Schema.Struct({ id: Schema.String, price: Schema.Number });

// Every new array is a change, even one equal part by part.
const $log = schemaBox(realm, Schema.Array(Schema.String), [], { equals: Object.is });

// The same row while the id is the same, whatever the price.
const $selected = schemaBox(
  realm,
  Row,
  { id: "a", price: 1 },
  { equals: (held, next) => held.id === next.id },
);
```

## Rules

- The core's `box`, `collection`, and `computed` compare with `Object.is`
  unless `{ equals }` says otherwise, so a new array or object is a change.
  A computed value compares with `Object.is` in `pinna-effect` too, even
  when what it reads is a `schemaBox`.
- A `schemaBox` and a `BoxField` compare with the schema's equivalence,
  with the answers of `Schema.toEquivalence`. An equal write keeps the
  value held and notifies nobody, so a refetch of the same data reruns
  nothing.
- Under a schema's equivalence a primitive equals the same value, `NaN`
  equals `NaN`, and `0` equals `-0`. A `Date` equals one with the same time,
  and two invalid Dates are equal. An array or a struct compares part by
  part. A schema with an equivalence annotation, such as
  `Schema.overrideToEquivalence`, compares with it.
- A box of `Schema.Unknown`, `Schema.Any`, or `Schema.ObjectKeyword`
  compares with `Object.is`: such a schema says nothing of the value's
  shape, and a structural compare would hash the whole value on every
  write. An `Unknown` field inside a struct compares structurally.
- `{ equals }` replaces the schema's equivalence: `Object.is` counts every
  new array or object as a change, even one equal part by part, and a
  function by id counts a row with a new price as unchanged.
- A `SchemaModel` instance without its own `Equal` compares its plain fields
  by value and its boxes and its realm by identity. Every `decode` makes new
  boxes, so a refetched instance with a `$` field is not equal to the one
  held, and neither is an instance from another realm.
- A `SchemaModel` with its own `[Equal.symbol]` is compared by that method
  wherever Pinna compares with the class's schema, as in a `schemaBox` and
  in `reconcileSchema`, on every comparison, with no answer cached. A plain
  `Schema.Class` ignores its own `[Equal.symbol]` there, as Effect's schema
  does, and compares field by field.
- A refetched `SchemaModel` instance under a held key is merged into the
  held one when both are of the same class and realm and their plain fields
  are equal, or the class's own `[Equal.symbol]` finds them equal, even
  when a plain field differs. The held instance stays; each `BoxField`
  takes the refetched value, compared with its schema, and each
  `CollectionField` merges its rows the same way, so a refetch reruns only
  the readers of a box that changed. A plain field that holds a model is
  compared, not merged. Any other difference replaces the instance.
- `reconcileSchema`, `write.replaceAll`, and `write.upsert` merge. A
  `schemaBox` of an array compares by index and does not.
- A `CollectionField` merges a `SchemaModel` row written under a held key
  and compares any other row with the row schema's equivalence: `replaceAll`
  and `upsert` keep every equal or merged row, and notify nobody when
  nothing changed.
- `reconcile` takes `equals` and has no default: a refetch builds new
  objects, and the comparison is the caller's choice.
- `reconcileSchema` keeps a row that is the same instance, merges a
  `SchemaModel` row, compares any other instance of a `Schema.Class` with
  its class's equivalence, and anything else with Effect's `Equal.equals`.
  A key repeated in the new array throws before any box is written. The
  merge writes in the open update, or in one of its own; a refetch that
  changes no box opens none, so it runs inside a computed value too.
  `equals` replaces all of it.
- Effect's `Equal.equals`, which `HashSet` and `HashMap` look values up
  with, is not the schema's equivalence. It compares `Hash.hash` first,
  caches each object's hash, caches its answer for a pair of objects, and
  compares an instance by every own property. The two agree on a plain
  `Schema.Class` and on a `SchemaModel` whose fields are all plain: two
  decodes of the same JSON into one realm are equal, and `HashSet.has`
  finds either. They part on two cases:
  - A `$` property of the class body, such as a computed value, is no
    schema field. The schema's equivalence ignores it; `Equal.equals`
    compares it by identity, so two instances are not equal under Effect.
  - A `SchemaModel` with `[Equal.symbol]` and no `[Hash.symbol]` is equal
    under the schema's equivalence and not under `Equal.equals`, which
    compares hashes first. Define both, on plain fields only, such as the
    key, since Effect caches the hash.
- Under Effect's `Equal.equals`, a box, a computed value, an atom, and a
  realm equal only themselves. A plain object holding them compares them by
  identity, never by their contents.

## Answers

| Call | Compares a new value with the held one by default with |
| --- | --- |
| `box(realm, initial, { equals? })` | `Object.is`. |
| `collection(realm, { keyOf, equals? })` | `Object.is`, row by row. |
| `computed(realm, compute, { equals? })` | `Object.is`. |
| `schemaBox(realm, schema, initial, { equals? })` | The schema's equivalence. |
| `BoxField(schema)` | The schema's equivalence. |
| `CollectionField(schema, { keyOf })` | A merge for a `SchemaModel` row, the row schema's equivalence otherwise, row by row. |
| `reconcile(previous, next, { keyOf, equals })` | `equals`, required. |
| `reconcileSchema(previous, next, { keyOf, equals? })` | A merge for a `SchemaModel` row, the class's equivalence for another schema class instance, `Equal.equals` otherwise. |

## See also

- [Schema-checked boxes](./boxes.md): the box that checks a schema on every write.
- [Classes](./classes.md): the model whose fields these rules compare.
- [Collection fields](./collections.md): `replaceAll` and `reconcile` on a refetch.
- [Boxes and computed](../state/boxes.md): the core's box and its `equals`.
- [Collections](../state/collections.md): the core's collection and its `equals`.
