Store Counter
Minimal example showing how to use the global simulation store (ctx.store) to accumulate custom data across event handlers.
What it demonstrates
- Typed global store (
TStoregeneric) - Initializing the store via
options.store - Mutating
ctx.storeinside handlers - Reading the final store from
result.store
Code
import { SimulationEngine } from 'simloop';
type Events = {
tick: { value: number };
};
type Store = {
count: number;
total: number;
};
const sim = new SimulationEngine<Events, Store>({
store: { count: 0, total: 0 },
logLevel: 'silent',
});
sim.init((ctx) => {
ctx.schedule('tick', 1, { value: 10 });
ctx.schedule('tick', 2, { value: 20 });
ctx.schedule('tick', 3, { value: 30 });
});
sim.on('tick', (event, ctx) => {
ctx.store.count++;
ctx.store.total += event.payload.value;
});
const result = sim.run();
console.log('Events processed:', result.totalEventsProcessed); // 3
console.log('Store:', result.store); // { count: 3, total: 60 }Key takeaways
- The store is deep-cloned via
structuredCloneon init, soreset()always restores the original state. - The store is available in all handlers and hooks via
ctx.store. - The final store state is returned in
result.store.
Last updated on