(debug?: string)
| 23 | const DEV_DEBUG_EVENTS = false; |
| 24 | |
| 25 | export function createEventsEmmiter< |
| 26 | EventsMap extends Record<string, unknown[]> |
| 27 | >(debug?: string): EventsEmmiter<EventsMap> { |
| 28 | const subscribersMap = new Map< |
| 29 | keyof EventsMap, |
| 30 | Set<EventHandler<unknown[]>> |
| 31 | >(); |
| 32 | |
| 33 | function getHandlersForEvent<N extends keyof EventsMap>( |
| 34 | name: N |
| 35 | ): Set<EventHandler<EventsMap[N]>> { |
| 36 | const existingSet = subscribersMap.get(name); |
| 37 | |
| 38 | if (existingSet) return existingSet; |
| 39 | |
| 40 | const newSet = new Set<EventHandler<unknown[]>>(); |
| 41 | |
| 42 | subscribersMap.set(name, newSet); |
| 43 | |
| 44 | return newSet; |
| 45 | } |
| 46 | |
| 47 | function on<N extends keyof EventsMap>( |
| 48 | name: N, |
| 49 | handler: EventHandler<EventsMap[N]> |
| 50 | ) { |
| 51 | const listeners = getHandlersForEvent(name); |
| 52 | |
| 53 | listeners.add(handler); |
| 54 | |
| 55 | return () => { |
| 56 | listeners.delete(handler); |
| 57 | }; |
| 58 | } |
| 59 | |
| 60 | function onOneOf<N extends keyof EventsMap>( |
| 61 | names: N[], |
| 62 | handler: EventHandler<EventsMap[N]> |
| 63 | ) { |
| 64 | const cleanup = createCleanupObject(); |
| 65 | |
| 66 | for (const name of names) { |
| 67 | cleanup.next = on(name, handler); |
| 68 | } |
| 69 | |
| 70 | return () => { |
| 71 | cleanup.clean(); |
| 72 | }; |
| 73 | } |
| 74 | |
| 75 | function hasListeners<N extends keyof EventsMap>(name: N) { |
| 76 | return !!subscribersMap.get(name)?.size; |
| 77 | } |
| 78 | |
| 79 | function emit<N extends keyof EventsMap>(name: N, ...data: EventsMap[N]) { |
| 80 | if (IS_DEV && DEV_DEBUG_EVENTS && debug) { |
| 81 | console.warn(`Event [${debug}]`, name, data); |
| 82 | } |
no outgoing calls
no test coverage detected