State and Workflow Patterns
Command Dispatch Case
A discriminated command type keeps each action branch visible.
Command Dispatch Case
commands.ts
type Command =
| { kind: "add"; amount: number }
| { kind: "subtract"; amount: number }
| { kind: "reset" };
function applyCommand(total: number, command: Command): number {
if (command.kind === "add") {
return total + command.amount;
}
if (command.kind === "subtract") {
return total - command.amount;
}
return 0;
}
const useReset: boolean = ;
const commands: Command[] = [
{ kind: "add", amount: 5 },
useReset ? { kind: "reset" } : { kind: "subtract", amount: 2 },
{ kind: "add", amount: 3 }
];
let total: number = 0;
for (const command of commands) {
total = applyCommand(total, command);
}
console.log(`total=${total}`);
type Command =
| { kind: "add"; amount: number }
| { kind: "subtract"; amount: number }
| { kind: "reset" };
function applyCommand(total: number, command: Command): number {
if (command.kind === "add") {
return total + command.amount;
}
if (command.kind === "subtract") {
return total - command.amount;
}
return 0;
}
const useReset: boolean = ;
const commands: Command[] = [
{ kind: "add", amount: 5 },
useReset ? { kind: "reset" } : { kind: "subtract", amount: 2 },
{ kind: "add", amount: 3 }
];
let total: number = 0;
for (const command of commands) {
total = applyCommand(total, command);
}
console.log(`total=${total}`);
command dispatch
Dispatching by command kind is a traceable way to apply several updates in order.