The compute graph
There are two kinds of node:
- A computed is a slot (
TOIMComputedSlot) that publishes a value. It is refreshed when a reader asks for the value. - A
TOIMEffectpublishes nothing. A frame runs it, throughOIMEffectService.INSTANCE.
| You want | Take | Not |
|---|---|---|
| one derived value with no key (a total, a flag, a summary) | createOIMSingleComputedService<V>({ … }) and its createStoreSlot(db, derive, createSources), read through the service itself | a Map computed store slot read under a constant key |
| one derived value per key (per card, per deck, per user) | createOIMComputedService<K, V>({ … }) and its createStoreSlot(db, derive, createSources) | one single computed per key held in a Map of your own |
| a bucket's members as an array, in the order the caller wrote | createOIMBucketMemoComputedService and its createBucketMemoStoreSlot(bucketStoreSlot) | a computed that copies the bucket by hand |
| an index's members sorted | createOIMSortedComputedService and its createSortedStoreSlot(indexStoreSlot) | sorting inside an effect body on every run |
| something to happen when data moves (render, log, sync) | effectService.createEffect / createAndRunEffect | a computed whose derive has side effects |
| something to happen when one column of one entity moves | effectService.createEffect(db, body, [column]) | an effect over the whole entity slot |
Setup shared by the examples on this page
import { OIMDB, OIMEffectService, OIMSlotNeverReleasePolicy, createOIMSortedCollectionSingleSlotStoreAggregate, createOIMComputedService, createOIMSingleComputedService, createOIMSingleSourceTrackingComputedService, createOIMBucketMemoComputedService, createOIMSortedComputedService, createOIMSlotCollectionIndexService, isOIMSameValueZero, type TOIMEntitySlot, type TOIMStoreKey, createOIMEntityContentService, createOIMSlotCollectionService, OIMPositionalArrayBucketContentService, OIMBucketCommands } from '@oimdb/core';
type Card = { id: string; title: string; rank: number };
declare function use(value: number): void;
declare function render(value?: unknown): void;
const db = new OIMDB();
const effectService = OIMEffectService.INSTANCE;
const cardService = createOIMSlotCollectionService({ slotContentService: createOIMEntityContentService<Card>() });
const cards = cardService.createStoreSlot(db);
const slot = cardService.getSlotByKey(cards, 'c1');
const other = cardService.getSlotByKey(cards, 'c2');
const totalService = createOIMSingleComputedService<number>();
const total = totalService.createStoreSlot(
db,
() => (slot.entity?.rank ?? 0) + (other.entity?.rank ?? 0),
() => ({ sourceSlots: [slot, other] }),
);
const totalSlot = totalService.getSingleSlot(total);
A derivation is a slot that nothing marks
const rankService = createOIMSingleComputedService<number>({
sameValueGuard: isOIMSameValueZero, // did the derived value move?
});
const rank = rankService.createStoreSlot(
db,
() => slot.entity?.rank ?? 0,
() => ({
sourceSlots: [slot], // the root slots it reads
}),
);
const rankSlot = rankService.getSingleSlot(rank);
rankSlot.value; // settles, then answers
createSources returns sourceSlots (the root slots it reads) and sourceComputeds (the derivations it reads). Both keys are optional; a missing one means none.
A computed is a TOIMComputedSlot<TValue, TKey>. Its value is read as computedSlot.value,
a getter over the computed's value service, so it settles the computed first. Inside a tracked body the same read makes the computed a source.
Nothing schedules or marks a computed, and no frame walks to it. Whoever wants its value asks it: an effect deciding whether to run its body, or another computed doing the same. That is the whole lifecycle.
A computed slot holds every source it names while it lives, and gives them back when it is released. The slot goes when nothing holds it; the store slot lives on and mints a fresh one on the next read or hold.
Why a computed is pulled
A write marks a root slot — an entity, a bucket, a column — and wakes the
effects filed on it. It never visits a computed. An effect that names a computed
is filed on the computed and on every root underneath it: at construction the
effect walks its sourceComputeds down to their sourceSlots, collects each
root once, and subscribes to and holds each of them. So a write reaches the
effect directly, and the effect, before deciding to run, asks each computed it
names for its value — which settles that computed's own sources first, and so on
down.
What this buys:
- A computed nobody reads never derives. There is no dirty flag to propagate and no list of dependents to walk on a write; a write costs the same whether ten computeds sit over that root or none.
- At most one derive per clock tick. A settled computed remembers the clock reading it was checked at, and a second read at the same reading returns at once. Ten effects reading one computed in one frame, with no write between them, derive it once.
- No reader sees a half-updated graph. A computed settles its sources before it compares their stamps, so the order of evaluation is the order of the dependencies, decided by the reader's own recursion, not by a scheduler that has to sort the graph.
The cost is on the other side: an effect over a deep chain is filed on every root under it, and asks the chain on every wake. A chain whose roots did not move answers with stamp comparisons and no derive (below).
What it asks before it derives
Has anything I read moved? Every source computed is settled on the way past, in that order: a root answers "did I move" from a stamp it already carries and a computed cannot, so a computed source is settled before its stamp is read.
A chain short-circuits. A recursive settle returns on that one question
when nothing under it moved, without deriving — so a chain over quiet roots is a
walk of integer comparisons, and a chain whose roots moved derives only the
levels whose inputs actually changed. That is what makes filter → sort → page
cost one comparison when an entity moves without leaving the filter, instead of
sorting everything again.
A cycle through sourceComputeds cannot be built: a computed's sources are
fixed by createSources, which runs before the slot exists, so the slot
cannot be among them. A read of the slot from inside its own derive answers the
previous computedSlot.value without deriving.
sameValueGuard is what buys the short-circuit
isOIMSameValueZero is === with NaN equal to itself. Pass your own when the
derived value is a structure:
const idsService = createOIMSingleComputedService<readonly string[]>({
sameValueGuard: (prev, next) => prev.length === next.length && prev.every((v, i) => v === next[i]),
initialValue: [],
});
idsService.createStoreSlot(
db,
() => [slot, other].flatMap((cardSlot) => (cardSlot.entity === undefined ? [] : [cardSlot.entity.id])),
() => ({ sourceSlots: [slot, other] }),
);
sameValueGuard decides whether the readers of the computed are told: when it answers
true, the previous value is kept by identity and the slot does not count as
changed, so every reader above stops at its comparison. Left out, it is
Object.is. A body that throws leaves the computed exactly as it was and the next
read tries again.
A computed as a source
A source computed is a slot taken from its own collection. Every source list in this
engine — createEffect's sourceComputeds argument, sourceComputeds in
createSources — is typed readonly TOIMComputedSlot[], so a typed slot goes in
as it is:
effectService.createEffect(db, () => { use(totalSlot.value); }, [], [totalSlot]);
const doubledService = createOIMSingleComputedService<number>();
const doubled = doubledService.createStoreSlot(
db,
() => totalSlot.value * 2,
() => ({ sourceComputeds: [totalService.getSingleSlot(total)] }),
);
Inside derive, computedSlot.value is the previous value, which is what a
sameValueGuard compares the new one against.
Both shapes are factories
The computed is the slot, and the slot dies when nothing holds it.
OIMComputedService and the store slots it creates are the factories that own it:
the value service holds the sameValueGuard once, a store slot holds
its derive function and its channel slot, both outlive every slot they mint, and when the previous slot is
gone the next read or hold mints a fresh one — by key in a keyed store slot, under the key undefined in a
single one.
A slot goes when nothing holds it, and a computed slot holds its sources while it lives. A computed that lived as long as the object you created would hold its sources for as long as you kept that object, and every entity it ever read would stay in memory. So the long-lived things are the service and the store slot, which hold nothing, and the computed is what they hand out: a slot that lives while something holds it or an effect reads it, and gives its sources back when it goes.
What follows for a caller:
- Keep the store slot. A slot reference outlives the slot.
getValueForSlot,holdSlotandunholdSloton a released slot throw ("This identity was released"). Ask the service again —computedService.getSlotByKey(storeSlot, key)/holdSlotByKey(storeSlot, key), with the keyundefinedfor a single — and it hands back the live slot, or mints a new one. createSourcesruns once per mint, and a store slot mints many times. A new slot names its sources afresh and takes fresh holds on them.- A new slot starts from
initialValueand derives on its first read; the value of a slot that went is not carried over.
Releasing a computed and its sources
A computed slot goes when its holds are back, no effect is on it, and its release policy agrees. Going gives back the hold it took on each of its sources, and each source's owner may then let that source go, one level at a time.
The default for a computed is OIMSlotAtUnholdReleasePolicy.INSTANCE, used by every computed factory when
no slotReleasePolicy is passed; the computed factories take no db, so the OIMDB's policy does not
reach a computed. The entity collections' default is OIMSlotAtEmptyReleasePolicy.
A computed slot is never empty — its emptiness check answers false — so
OIMSlotAtEmptyReleasePolicy and OIMSlotNeverReleasePolicy keep it, and every
source under it, for the life of the store slot. Without a time policy a computed
slot goes at its last unhold or effect detach, or at the next flush when it was
only read. The policies are listed in
Slot lifecycle.
const pinnedTotalService = createOIMSingleComputedService<number>({
slotReleasePolicy: OIMSlotNeverReleasePolicy.INSTANCE,
});
const pinnedTotal = pinnedTotalService.createStoreSlot(
db,
() => (slot.entity?.rank ?? 0) + (other.entity?.rank ?? 0),
() => ({ sourceSlots: [slot, other] }),
);
const pinnedTotalSlot = pinnedTotalService.getSingleSlot(pinnedTotal);
pinnedTotalSlot.value;
Use OIMSlotNeverReleasePolicy for a computed that every screen reads and that is cheap to keep;
leave the default for one that belongs to a view that comes and goes. The policy
belongs to the collection type, so every store slot of that service shares it. The options
of the policies that take a window are in
Releasing an identity on a clock.
createOIMSortedComputedService and createOIMBucketMemoComputedService take a slotReleasePolicy too.
Releasing a computed value
A derived value can hold something that has to be given back: a request in flight, a subscription, a
timer. releaseValue is the option for it, next to derive and createSources, of type
TOIMComputedValueReleaser<TValue>. It is called with a value the computed no longer keeps:
| What happened | Called with |
|---|---|
derive produced a value sameValueGuard calls different | the previous value |
derive produced a new object sameValueGuard calls equal | that new object — it is dropped and the slot keeps the old one |
derive returned the object the slot already holds | nothing is called |
| the computed slot is released | its current value |
the slot was released while its own derive ran | the value that derive returned, which is not stored |
initialValue is never passed: derive did not make it.
type Query = { key: string; abort: () => void };
declare function startQuery(key: string): Query;
const queryService = createOIMComputedService<string, Query>({
derive: computedSlot => startQuery(computedSlot.key),
createSources: computedSlot => ({ sourceSlots: [cardService.getSlotByKey(cards, computedSlot.key)] }),
releaseValue: query => { query.abort(); },
});
The last unhold of a query's slot aborts it, under the default OIMSlotAtUnholdReleasePolicy; with
OIMSlotAfterUnholdReleasePolicy the query survives a let-go-and-take-again inside its window. The default
releaseValue gives back nothing.
Effects
OIMEffectService.INSTANCE.createEffect and createAndRunEffect are how an effect is built, and
subscribing is one of the four minting doors.
createEffect alone never runs its body at creation; createAndRunEffect runs it once
immediately and, if that run throws, disposes the effect and rethrows. An effect created
while the open frame already has writes is scheduled for
that frame's flush, but it does not receive writes made before it was created. The
effect service is stateless — there is one, OIMEffectService.INSTANCE — and each door takes the channel
map (db) first; an effect is a plain TOIMEffect object with no methods. When all you keep is the way to
stop it, effectService.subscribeEffect(db, body, sourceSlots?, sourceComputeds?, sourceTrackingComputeds?) builds the same effect and returns
its TOIMDisposer.
const effect = effectService.createEffect(
db, () => { render(); }, [slot, other], [totalSlot],
);
effectService.disposeEffect(effect);
An effect holds every slot it is filed on — the roots you name, the roots under the derivations you name, and the derivations themselves — so nothing it reads goes while it stands, whatever the release policy. Use an effect for what leaves the graph (a render, a network call, a log); a value another part of the graph reads belongs in a computed, because an effect's result has no slot anyone can name as a source.
The body runs when something it reads has moved. An effect counts as having run
only after its body returns, so a body that threw takes the same change again at
its next wake. disposeEffect takes the effect off every root's
dependent list and asks each root's owner whether it may go, which may empty the
dependent list of a derivation below it, and so on down. That is where a chain
comes apart, one level at a time, driven by the same call.
An effect has no dispose of its own; a detached disposer is () => effectService.disposeEffect(effect),
or the one subscribeEffect hands back — see giving handles back.
Naming one computed slot twice in sourceComputeds files the effect on it once.
disposeEffect is O(1) per source, so a slot's effects list is not in subscription order.
The body's type is TOIMEffectBody — () => (() => void) | void. Return a
function and it is run before the next run of the body and by disposeEffect, so a body
that opened something per run has somewhere to close it. See
a body may hand back its own undo.
An effect over one column
effectService.createEffect(db, () => { render(); }, [slot.holdColumnSlot('rank')]);
It takes the column slot and a body, and wakes only when that column moves. See Reading and subscribing.
An effect that finds its sources as it reads
createEffect takes its sources up front. createSourceTrackingEffect(db, body) takes
none: every slot or derivation the body reads becomes a source of that run. This is how a signal library tracks
dependencies, and it fits a body whose reads depend on the data — a branch, a lookup
that names a different slot next time.
const showTotal = cardService.getSlotByKey(cards, 'settings');
effectService.createSourceTrackingEffect(db, () => {
const isTotalShown = showTotal.entity?.rank === 1;
render(isTotalShown
? totalSlot.value
: slot.entity?.title);
});
- Reading is the subscription:
slot.entityon an entity slot,computed.valueon a derivation and a bucket slot's membership reads (bucket.getBucketMemberSlots(),getBucketMemberSlotCount(),hasBucketMemberSlot(member),getBucketMemberSlotsMissingFrom(members)).computed.valuemakes the computed itself a source, so the run refreshes it before deciding to run. - A read through a service door that takes the slot as an argument
(
slotContentService.…(slot)) is not tracked; read through the slot. - A tracked read of
entitymakes the whole entity a source. To wake on some columns only, readcardSlot.getEntity(columnGroup): the same entity, with only that group's columns as the source. Build the group once, outside the body (createOIMColumnGroup(names)); a group is compared by identity.getEntitytakes any group; it need not be declared on the service. - The body runs once at creation, because the first run is what finds the sources.
- After each run the effect is subscribed to exactly what that run read. A branch the run did not take is unsubscribed, and a slot read twice is subscribed once.
- A run that reads the same sources in the same order as the run before compares each
read with the previous one and changes no subscription. A run that diverges looks each read up
among its sources so far: a scan up to 16 distinct sources, a
Mapbeyond. createEffectis unchanged. The two are picked per effect, at creation: declared sources where the dependencies are known, tracked sources where they move with the data.- The body's type is
TOIMSourceTrackingEffectBody—() => (() => void) | void; a returned function is the undo, as forcreateEffect.
A derivation that finds its sources as it reads
createOIMSingleSourceTrackingComputedService({ derive }) and the keyed
createOIMSourceTrackingComputedService({ derive }) build derivations with no createSources: what
derive reads — slot.entity, computed.value, a bucket slot's membership — is what it depends on.
const shownTitleService = createOIMSingleSourceTrackingComputedService<string>({
derive: () => slot.entity?.rank === 1
? slot.entity?.title ?? ''
: other.entity?.title ?? '',
initialValue: '',
});
const shownTitle = shownTitleService.holdSingleSlot(shownTitleService.createStoreSlot(db));
effectService.createSourceTrackingEffect(db, () => {
render(shownTitle.value);
});
- Each derive holds what it read and lets go of what it no longer reads; the new holds are taken before the old ones are given back, so a source read by both derives never reaches a hold count of zero.
- It is read through a source tracker (
createSourceTrackingEffect, or another source-tracking derivation'sderive), or through the fifth list ofcreateEffectbelow. Its slot type,TOIMSourceTrackingComputedSlot(keyed) orTOIMSourceTrackingComputedContentSlot(single), is refused bycreateEffect'ssourceComputedsand by acreateSourceslist: an effect over declared sources subscribes once to the slots under a derivation and never looks again, so a derivation whose sources move would leave it subscribed to the old ones. - When a derive switches sources, a source-tracking effect over it re-subscribes even if the derived value is the same, and so does a source-tracking derivation over it.
- A declared effect over it: the fifth list of
createEffect(db, body, sourceSlots, sourceComputeds, sourceTrackingComputeds). PrefercreateSourceTrackingEffect. The list exists for a body that cannot read through a tracker. An effect given one derives every listed computed at creation and, after every run and on every frame where the value held, compares each computed's root slots with the ones it subscribed to, and re-subscribes when they were replaced. An effect without that list does none of this, which is whysourceComputedsrefuses a source-tracking computed. The fifth list itself takes any computed, a plain one included. sameValueGuard,releaseValue,initialValue,slotReleasePolicyand the column options are the same as forcreateOIMSingleComputedService. There is nocreateSources, andcreateStoreSlot(db)takes no per-storederive.
One derivation, no key
Setup shared by the examples on this page
const topRankService = createOIMSingleComputedService<number>({
sameValueGuard: isOIMSameValueZero,
initialValue: -1,
});
const topRank = topRankService.createStoreSlot(
db,
() => cardService.getSlotByKey(cards, 'c1').entity?.rank ?? -1,
() => ({ sourceSlots: [cardService.getSlotByKey(cards, 'c1')] }),
);
const heldTopRank = topRankService.holdSingleSlot(topRank); // minted once; the same slot while anything holds it
heldTopRank.unholdSlot(); // gone; the next holdSingleSlot(topRank) mints a new one
createOIMSingleComputedService<TValue>({ sameValueGuard?, initialValue?, slotReleasePolicy?, derive?, createSources?, columnSlotStoreService? | columnNames? })
builds an OIMSingleComputedService, whose store slots each hold at most one computed slot.
createStoreSlot(db, derive?, createSources?) creates one single computed and mints
nothing; a derive or createSources given to the store slot is used in place of the
service's, and each must come from one of the two.
sameValueGuard defaults to Object.is. A single is read through the service itself (it extends OIMSingleSlotService) —
getSingleSlot(storeSlot) (a slot without a hold, so a fresh one is let go at the next flush
unless something holds it), holdSingleSlot(storeSlot) and peekSingleSlot(storeSlot),
which mints nothing. A slot's give-back is slot.unholdSlot(), and its value
is slot.value. The slot is minted on the first get or hold
and released at its release policy, as in a collection, and the next get or hold mints a fresh one.
createSources is handed the computed slot, which is how a keyed one learns its key.
One derivation per key
Setup shared by the examples on this page
const rankByIdService = createOIMComputedService<TOIMStoreKey, number>({
sameValueGuard: isOIMSameValueZero,
initialValue: -1,
});
const ranks = rankByIdService.createStoreSlot(
db,
(computedSlot) => cardService.getSlotByKey(cards, computedSlot.key).entity?.rank ?? -1,
({ key }) => ({ sourceSlots: [cardService.getSlotByKey(cards, key)] }),
);
createOIMComputedService(options) takes no db. On a keyed service every option is
optional: derive and createSources (the defaults for every store slot that is given
none), slotStoreService (the store the derivation slots are filed in; a Map store when left out,
and required for any other store), sameValueGuard (default Object.is),
initialValue, slotReleasePolicy and columnSlotStoreService or
columnNames (left out, a shared map-driven store); left out, a
derivation goes at its last unhold (OIMSlotAtUnholdReleasePolicy). createStoreSlot(db, derive?, createSources?)
refuses by name when neither it nor the service has a derive and a createSources.
A last unhold that lands while the channel is
flushing releases the derivation on the spot, as it does for every slot.
createSources takes the key, and declares the sources of the
slot it is minting, as a TOIMComputedSources — { sourceSlots, sourceComputeds }. It does not hold them
itself. The owner takes a hold on every slot in sourceSlots and every entry in
sourceComputeds the moment it creates the slot, and gives exactly those
back when it releases the slot — so a source stands for as long as the derivation
is filed and never passes through zero references.
That is why createSources resolves through getSlotByKey and not holdSlotByKey: a hold
it took for itself is one nobody gives back. getSlotByKey
hands its mint to the unused-slot collector, which lets go at the next flush, by
which time the owner's own hold is standing.
derive receives the computed slot, so it reads computedSlot.key to know which
key it is deriving — one function serves every key.
The computed collection service files a keyed store slot's derivations the way the entity and bucket collections file theirs, so it has the same keyed doors, each taking the store slot first:
const heldRank = rankByIdService.holdSlotByKey(ranks, 'c1'); // built once; the same object while anything holds it
rankByIdService.getSlotByKey(ranks, 'c9'); // the derivation, built if 'c9' had none; the collector tracks the mint
rankByIdService.getSlotCount(ranks);
for (const derivation of rankByIdService.getSlots(ranks)) { use(derivation.value); }
heldRank.value; // settles, then answers
heldRank.unholdSlot(); // the give-back; there is no release call on a derivation
A derivation is never empty, so what decides when one may go is the hold count, the effects on it, and the release policy.
Computed columns
A computed's value can be subscribed to by field. A computed's slot carries the same six column
doors an entity slot does — getColumnSlot(columnName), holdColumnSlot(columnName),
getColumnGroupSlot(group), holdColumnGroupSlot(group) (a group named in the factory's
columnGroups) and getAnyColumnSlot() / holdAnyColumnSlot() — and the computed service's
columnSlotService has them with the slot first, next to unholdColumnSlot(columnSlot). That slot's type is
TOIMComputedCarrierSlot: TOIMComputedContentSlot plus the doors and watch; a single computed
service hands it out. Column names are typed as the keys of the value. The sorted and bucket-memo factories
take columnNames and columnGroups too, but their value is an array of slots, so a column of it is a key of
the array — length, say — not a field of the members.
A computed's column slot is the same OIMColumnSlot an entity's is, pulled instead of pushed:
TOIMComputedColumnSlot is a computed whose value is carrier.value[column] compared with
Object.is. It goes in the sourceComputeds list of createEffect and wakes an effect only when
that field of the derived value changes. Entity and bucket column slots go in the root list instead.
TOIMComputedColumnSlot<TSourceTracker> carries its carrier's tracker type, so a column of a
source-tracking computed is refused by the sourceComputeds list and accepted by the
sourceTrackingComputeds list, the way its carrier is.
type CardSummary = { top: number; count: number };
const cardSummaryService = createOIMSingleComputedService<CardSummary>();
const cardSummary = cardSummaryService.createStoreSlot(
db,
() => ({ top: Math.max(slot.entity?.rank ?? 0, other.entity?.rank ?? 0), count: cardService.getSlotCount(cards) }),
() => ({ sourceSlots: [slot, other] }),
);
const topColumn = cardSummaryService.getSingleSlot(cardSummary).holdColumnSlot('top');
const onTop = effectService.createEffect(db, () => { render(topColumn.value); }, [], [topColumn]);
effectService.disposeEffect(onTop);
topColumn.unholdSlot();
The order of a bucket is a derivation
A bucket never sorts: its order is the one the caller wrote. Two derivations read it, and both are subscribed to rather than the bucket.
The bucket's own order, as an array: createOIMBucketMemoComputedService. Take it
over an array-driven bucket collection whose order the caller writes (a playlist, a
hand-arranged board) when the consumer wants an array:
Setup shared by the examples on this page
const byDeckService = createOIMSlotCollectionService({ slotContentService: new OIMPositionalArrayBucketContentService<TOIMEntitySlot<Card>>({ bucketCommands: new OIMBucketCommands({ maxCommandsPerSlot: undefined }) }) });
const byDeck = byDeckService.createStoreSlot(db);
const orderService = createOIMBucketMemoComputedService({
bucketCollectionService: byDeckService,
});
const order = orderService.createBucketMemoStoreSlot(byDeck);
const deck = orderService.holdSlotByKey(order, 'spades'); // mints and holds the bucket too
effectService.createAndRunEffect(db, () => render(deck.value), [], [deck]);
createOIMBucketMemoComputedService(options) takes no db: a memo store slot runs on the channel slot of
the bucket store slot it reads. The options object has one required key, bucketCollectionService, the
bucket collection the orders read; createBucketMemoStoreSlot(bucketStoreSlot) then names the bucket store
slot of that collection whose buckets it orders. slotStoreService (the store the orders are filed
in; a Map store when left out), slotReleasePolicy and columnSlotStoreService are optional.
Its value is that bucket's slots in the bucket's order, produced on the read that asks for it and never while nothing reads it. It counts as changed only when the list a reader would see actually changed. The array comes back by identity — the same one for as long as the list holds — so a consumer memoising on identity needs no comparison of its own. Its source list is one slot, the bucket, and it never grows.
A sorted list over an index: createOIMSortedComputedService.
const faceService = createOIMSlotCollectionIndexService({ entityService: cardService, selectKey: (card: Card) => (card.rank > 10 ? 'face' : 'number') });
const byFace = faceService.createIndexStoreSlot(cards);
const byRankService = createOIMSortedComputedService({
indexService: faceService,
sortColumns: [{ columnName: 'rank', direction: 'asc' }],
});
const byRank = byRankService.createSortedStoreSlot(byFace);
const faceCards = byRankService.holdSlotByKey(byRank, 'face');
effectService.createAndRunEffect(db, () => render(faceCards.value), [], [faceCards]);
A whole collection sorted needs no index: createOIMSortedCollectionSingleSlotStoreAggregate(entitySlotCollectionStoreAggregate, { sortColumns?, comparator? })
returns a single-slot aggregate whose getSingleSlot().value is every entity slot
in order.
const everyCardByRank = createOIMSortedCollectionSingleSlotStoreAggregate(cardService.createStoreAggregate(cards), {
sortColumns: [{ columnName: 'rank', direction: 'asc' }],
});
db.createEffect(() => render(everyCardByRank.getSingleSlot().value));
indexService is the OIMSlotCollectionIndexService the sorted list reads, and createSortedStoreSlot(indexStoreSlot)
names which of its index store slots. sortColumns (TOIMSortColumn<TEntity>[]) decide which writes re-sort;
comparator: (left, right) => number decides the order, and without it the order is
createOIMColumnsComparator(sortColumns). Its sources are the bucket slot of the key plus one
bucket column slot per column, so it re-sorts only when membership changes or a write
changes one of those columns on a member. Given only a comparator, its sources are the
bucket slot and the bucket's any-column slot, and any member write re-sorts. A re-sort that yields the same
sequence keeps the previous array. See Ordering.
sortColumns says when to sort and comparator says how. A comparator is a function the engine cannot look inside, so on its
own it cannot tell which writes could change the order and has to re-sort on every
member write. Naming the columns lets the engine subscribe to exactly those columns;
the comparator, when given as well, still decides the order.
| Given | Sources | Re-sorts on | Order |
|---|---|---|---|
sortColumns | bucket slot + one bucket column slot per column | membership, a write to a named column on a member | createOIMColumnsComparator(sortColumns) |
sortColumns + comparator | the same | the same | comparator |
comparator | bucket slot + the bucket's any-column slot | membership, any member write | comparator |
| neither | bucket slot | membership | a member keeps its place; an arrival is appended |
On a membership change the previous order is kept for the members that stayed and
the arrivals are appended before the sort runs; with no membership change the
previous array is copied and sorted again. An entity slot whose entity is gone sorts
last. Its slots are filed in a Map store unless the factory is given a slotStoreService.