1 · Model, solve and test · 25 MIN
Apply commands through an explicit state machine
Apply commands through an explicit state machine
A reducer computes the next state from a previous state and a command. This counter supports add and reset with different associated fields. An exhaustive never check makes an unhandled future command a type error in a full TypeScript build. Runtime tests verify transitions, while tsc verifies the compile-time exhaustiveness claim. Keep side effects outside reducers so replaying commands produces the same final state.
Write one transition function, then reduce the command log through it.
Read the example
type Command={type:'add';amount:number}|{type:'reset'};
function apply(value:number,command:Command):number{switch(command.type){case 'add':return value+command.amount;case 'reset':return 0;default:{const unreachable:never=command;return unreachable}}}
function solve(input:{initial:number;commands:Command[]}):number{return input.commands.reduce(apply,input.initial)}
console.log(JSON.stringify(solve({"initial":5,"commands":[{"type":"add","amount":3},{"type":"reset"},{"type":"add","amount":2}]})));Check the expected output
2
Your challenge
Input is {initial:number,commands:({type:"add",amount:number}|{type:"reset"})[]}. Apply commands in order and return the final number.
Solution cost: O(n) command transitions. time · O(1) accumulator state. space
Common trap
The browser transpiler does not run full semantic type checking; use tsc to verify never exhaustiveness.