-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathswitchcontext.ts
More file actions
27 lines (24 loc) · 833 Bytes
/
switchcontext.ts
File metadata and controls
27 lines (24 loc) · 833 Bytes
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
class SwitchContext {
private Cases: { Match: any, Handler: () => void, IsDefault?: boolean }[] = [];
addCase(match: any, handler: () => void): void {
this.Cases.push({ Match: match, Handler: handler });
}
addDefault(handler: () => void): void {
this.Cases.push({ Match: null, Handler: handler, IsDefault: true });
}
execute(value: any): void {
let matched = false;
for (let cb of this.Cases) {
if (cb.Match === value || cb.Match == value) {
cb.Handler();
matched = true;
break;
}
}
if (!matched) {
let defaultCase = this.Cases.find(cb => cb.IsDefault);
if (defaultCase) defaultCase.Handler();
}
this.Cases = []; // clear after execution
}
}