/
Evt.merge.ts
60 lines (43 loc) 路 1.6 KB
/
Evt.merge.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
58
59
60
type UnpackEvt<T extends ({ [key: string]: any; } | import("./types/helper/UnpackEvt.ts").EvtLike<any>)> =
import("./types/helper/UnpackEvt.ts").UnpackEvt<T>;
import { importProxy } from "./importProxy.ts";
type Evt<T> = import("./types/interfaces/index.ts").Evt<T>;
type CtxLike<Result> = import("./types/interfaces/index.ts").CtxLike<Result>;
export type EvtLike<T> = import("./types/helper/UnpackEvt.ts").EvtLike<T> & {
attach(ctx: CtxLike<any>, callback: (data: T) => void): void;
attach(callback: (data: T) => void): void;
};
export function mergeImpl<EvtUnion extends EvtLike<any>>(
ctx: CtxLike<any> | undefined,
evts: readonly EvtUnion[]
): Evt<UnpackEvt<EvtUnion>> {
const evtUnion = new importProxy.Evt<UnpackEvt<EvtUnion>>();
const callback = (data: UnpackEvt<typeof evtUnion>) => evtUnion.post(data)
evts.forEach(
evt => {
if (ctx === undefined) {
evt.attach(callback);
} else {
evt.attach(ctx, callback);
}
}
);
return evtUnion;
}
/** https://docs.evt.land/api/evt/merge */
export function merge<EvtUnion extends EvtLike<any>>(
ctx: CtxLike<any>,
evts: readonly EvtUnion[]
): Evt<UnpackEvt<EvtUnion>>;
export function merge<EvtUnion extends EvtLike<any>>(
evts: readonly EvtUnion[]
): Evt<UnpackEvt<EvtUnion>>;
export function merge<EvtUnion extends EvtLike<any>>(
p1: CtxLike<any> | readonly EvtUnion[],
p2?: readonly EvtUnion[]
): Evt<UnpackEvt<EvtUnion>> {
return "length" in p1 ?
mergeImpl(undefined, p1) :
mergeImpl(p1, p2!)
;
}