@amatiasq/state-delta
v0.1.0
Published
`diff` two JSON values, send the difference, `patch` it back. Made for state that travels thirty times a second: the delta carries only what changed, and a value the receiver can work out on its own costs nothing at all.
Readme
@amatiasq/state-delta
diff two JSON values, send the difference, patch it back. Made for state
that travels thirty times a second: the delta carries only what changed, and a
value the receiver can work out on its own costs nothing at all.
npm i --save @amatiasq/state-deltaUsage
import { diff, patch } from '@amatiasq/state-delta';
const delta = diff(previous, next);
if (delta !== undefined) send(JSON.stringify(delta));
// the other end
state = patch(state, JSON.parse(message));patch never mutates what it is given, so the previous state stays valid and a
delta that arrives twice is harmless.
The format
A delta is plain JSON and travels as it is:
| Delta | Means |
| ---------------- | ----------------------------------------------------- |
| undefined | nothing changed |
| [] | this is gone |
| [value] | replace the whole object or array with value |
| { $: n, 2: … } | an array of length n, with the indices that changed |
| anything else | the new value |
A replacement is wrapped in an array so it cannot read as a partial update:
{ a: 1 } says the key a changed, [{ a: 1 }] says the whole value is now
{ a: 1 }.
$ is reserved: an array delta keeps its new length there, so diff throws
on an object that uses that key rather than let it travel as something else.
UNCHANGED
UNCHANGED is the sender saying "skip this one, you can work it out yourself".
The key is left out of the delta and patch keeps whatever the receiver has —
zero bytes, not a marker or a code.
diff({ x: 0, hp: 3 }, { x: UNCHANGED, hp: 2 }); // { hp: 2 }The mirror invariant
Diff against what the receiver holds, never against the last value you built. The sender keeps a mirror of the receiver and moves it forward by patching the very delta it just sent:
const delta = diff(mirror, next);
mirror = patch(mirror, delta);
send(delta);That is what keeps a skipped value from rotting. Diff against your own truth instead and the field looks unchanged for ever: it never travels again, and the receiver keeps a value nobody is going to correct.
