Skip to content

Commit fa6a22c

Browse files
authored
Create switchcontext.ts ...
... to provide an easy way for EACH switchBlock to track their own caseBlock garage and all the entities within. Before, we were going to use a shared space, akin to a shared parking lot for all the switchBlocks in the "mall", with each switchBlock being akin to a store. This would have made things awkward and extremely difficult to maintain or even test safely with more than one switchBlock in use in a project/game. So, we are tackling that here and now before we wind up with s'ghetti code or worse, circular dependencies, **shudders** This class will depend upon content, logic, and assumptions that are present in other files and classes/functions/etc. This commit isn't to complete this step, nor to even hook it up with the main logic stream - instead, we are just placing the bricks, mortar, tools, and workers about the project so they will be ready at the time this is actually put together.
1 parent 6d30d42 commit fa6a22c

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)