Skip to Content

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 (TStore generic)
  • Initializing the store via options.store
  • Mutating ctx.store inside 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 structuredClone on init, so reset() 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