Skip to content

Commit 513bc04

Browse files
authored
Merge pull request #2 from seriussoft/seriussoft-patch-1
Create switchcontext.ts ...
2 parents d8623ec + 20aafa1 commit 513bc04

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

classes/switchcontext.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class SwitchContext {
2+
private Cases: { Match: any, Handler: () => void, IsDefault?: boolean }[] = [];
3+
4+
addCase(match: any, handler: () => void): void {
5+
this.Cases.push({ Match: match, Handler: handler });
6+
}
7+
8+
addDefault(handler: () => void): void {
9+
this.Cases.push({ Match: null, Handler: handler, IsDefault: true });
10+
}
11+
12+
execute(value: any): void {
13+
let matched = false;
14+
for (let cb of this.Cases) {
15+
if (cb.Match === value || cb.Match == value) {
16+
cb.Handler();
17+
matched = true;
18+
break;
19+
}
20+
}
21+
if (!matched) {
22+
let defaultCase = this.Cases.find(cb => cb.IsDefault);
23+
if (defaultCase) defaultCase.Handler();
24+
}
25+
this.Cases = []; // clear after execution
26+
}
27+
}

0 commit comments

Comments
 (0)