- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 38 lines of TypeScript from the credited upstream file 2694.ts.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1type Callback = (...args: any[]) => any;2type Subscription = {3 unsubscribe: () => void;4};5 6class EventEmitter {7 private eventToCallbacks: Map<string, Callback[]>;8 9 constructor() {10 this.eventToCallbacks = new Map();11 }12 13 subscribe(eventName: string, callback: Callback): Subscription {14 if (!this.eventToCallbacks.has(eventName))15 this.eventToCallbacks.set(eventName, []);16 17 const callbacks = this.eventToCallbacks.get(eventName);18 callbacks?.push(callback);19 20 return {21 unsubscribe: () => {22 const index = callbacks?.indexOf(callback);23 if (index !== undefined && index !== -1) {24 callbacks?.splice(index, 1);25 }26 },27 };28 }29 30 emit(eventName: string, args: any[] = []): any[] {31 const callbacks = this.eventToCallbacks.get(eventName);32 if (callbacks === undefined) {33 return [];34 }35 return callbacks.map((callback) => callback(...args));36 }37}38