All Challenges
1 PointBasicJavaScript Core
00:00
Robust Event Emitter with Wildcards & Scope Cleanup
Build a production-grade Pub/Sub Event Emitter supporting wildcard namespaces, listener priority, and auto-cleanup unsubscriptions.
### Problem Overview
Design and implement an industrial-strength **EventEmitter** class in TypeScript. Unlike basic naive implementations, your solution must prevent memory leaks, support wildcard event namespaces (e.g., `user.*` or `*`), and provide safe once-listeners and unsubscription tokens.
### Functional Requirements
1. **`on(event: string, listener: Function, options?: { priority?: number }): Subscription`**:
- Registers a listener for an event name.
- Returns a disposable subscription object with an `unsubscribe()` method.
- Listeners with higher priority must execute before lower priority listeners.
2. **`once(event: string, listener: Function): Subscription`**:
- Executes the listener at most once and automatically cleans itself up from the internal registry.
3. **`emit(event: string, ...args: any[]): boolean`**:
- Triggers all listeners registered for the exact event as well as wildcard pattern matches (e.g., emitting `"order.created"` triggers listeners for `"order.created"`, `"order.*"`, and `"*"`).
- Returns `true` if at least one listener was invoked, otherwise `false`.
4. **`off(event: string, listener: Function): this`**:
- Removes a specific listener.
5. **`listenerCount(event?: string): number`**:
- Returns the count of active listeners for a given event or total registered listeners if omitted.
### Non-Functional & Code Smell Guardrails
- **No Mutation During Iteration**: Emitting an event that removes or adds listeners must not corrupt the ongoing dispatch loop.
- **Memory Leak Prevention**: Unsubscribing must completely release references to allow Garbage Collection.
- **Error Boundary**: If one listener throws an error, other listeners should still execute unless configured otherwise.
AI Review Rubric Dimensions (1–10 Points):
- Wildcard regex/prefix matching
- Listener priority queue
- Unsubscribe memory leaks
- Re-entrancy / mutation safety
solution.tsTYPESCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
52 lines•1138 characters•
AI Review Ready