ts-09-typed-store
1.000
Proposed solution
```typescript
type Action = { type: "inc" } | { type: "add"; by: number };
export function createStore<S, A>(
reducer: (state: S, action: A) => S,
initial: S,
): {
getState(): S;
dispatch(action: A): void;
subscribe(fn: () => void): () => void;
} {
let state: S = initial;
let listeners: Array<() => void> = [];
function getState(): S {
return state;
}
function dispatch(action: A): void {
state = reducer(state, action);
listeners.forEach(fn => fn());
}
function subscribe(fn: () => void): () => void {
listeners.push(fn);
return () => {
const index = listeners.indexOf(fn);
if (index > -1) {
listeners.splice(index, 1);
}
};
}
return { getState, dispatch, subscribe };
}
```Test output (stdout)
TAP version 13 # Subtest: starts at the initial state ok 1 - starts at the initial state --- duration_ms: 0.376714 type: 'test' ... # Subtest: dispatch updates state via the reducer ok 2 - dispatch updates state via the reducer --- duration_ms: 0.079351 type: 'test' ... # Subtest: subscribers fire on every dispatch ok 3 - subscribers fire on every dispatch --- duration_ms: 0.060811 type: 'test' ... # Subtest: multiple subscribers all fire ok 4 - multiple subscribers all fire --- duration_ms: 0.341304 type: 'test' ... # Subtest: unsubscribe stops notifications ok 5 - unsubscribe stops notifications --- duration_ms: 0.070721 type: 'test' ... # Subtest: unsubscribing twice is harmless ok 6 - unsubscribing twice is harmless --- duration_ms: 0.084501 type: 'test' ... # Subtest: subscriber sees the updated state when notified ok 7 - subscriber sees the updated state when notified --- duration_ms: 0.311813 type: 'test' ... # Subtest: works with an object state shape ok 8 - works with an object state shape --- duration_ms: 0.083181 type: 'test' ... 1..8 # tests 8 # suites 0 # pass 8 # fail 0 # cancelled 0 # skipped 0 # todo 0 # duration_ms 80.936645
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.