-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventEmitter.ts
57 lines (47 loc) · 1.45 KB
/
eventEmitter.ts
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
53
54
55
56
57
export type Event = { type: string; payload?: unknown }
type InferPayload<E extends Event, Type> = E extends {
type: Type
payload: infer A extends E['payload']
}
? A
: undefined
type EmitFunction<E extends Event> = <
T extends E['type'],
Payload extends InferPayload<E, T> extends undefined ? [payload?: never] : [payload: Payload],
>(
event: T,
...args: Payload
) => void
type SubscribeFunction<E extends Event> = <
T extends E['type'],
Payload extends InferPayload<E, T>,
Fn extends E extends { type: T; payload: Payload } ? (payload: Payload) => void : VoidFunction,
>(
event: T,
fn: Fn,
) => () => void
export const createEventEmitter = <E extends Event>() => {
const listeners: Record<string, Set<(payload: E['payload']) => void>> = {}
const on: SubscribeFunction<E> = (event, fn) => {
listeners[event] ??= new Set()
listeners[event].add(fn)
return () => {
listeners[event].delete(fn)
}
}
const once: SubscribeFunction<E> = (event, fn) => {
const unsubscribe = on(event, ((payload: any) => {
unsubscribe()
;(fn as any)(payload)
}) as any)
return unsubscribe
}
const emit: EmitFunction<E> = (event, ...args) => listeners[event]?.forEach((fn) => fn(args[0]))
const remove = (event: E['type']) => delete listeners[event]
function clear() {
Object.keys(listeners).forEach((key) => {
listeners[key].clear()
})
}
return { listeners, on, once, emit, clear, remove }
}