Flatten Branching in TypeScript
Workflow
- •Identify nested conditionals, repeated guards, and duplicated mapping/serialization logic.
- •Use early return/continue to flatten nested blocks.
- •Extract small helpers for repeated conversions (timestamps, DTO mapping, error handling).
- •Replace repeated boolean gates with named flags (e.g.,
shouldRedact,isUnauthorized). - •Use
switchfor event-type fanout and delegate to small helpers where possible. - •Build arrays with optional entries plus
filter(Boolean)to avoid conditional pushes. - •Keep behavior identical: compare inputs/outputs and error messages before and after.
- •Run relevant tests; add or update tests only if behavior would otherwise be ambiguous.
- •Prefer small loader helpers that return
{ table, state } | nullto collapse repeated null checks. - •Use a shared unary wrapper for gRPC handlers to eliminate per-handler try/catch blocks.
Patterns
- •
Early return
- •Replace nested
ifblocks with guard clauses.
- •Replace nested
- •
Shared helpers
- •
mapEventToProto,timestampToDate,toTimestamp,mapCursorToProto.
- •
- •
Centralized error handling
- •One
handleErrorfor gRPC handlers to reduce per-handler branching.
- •One
- •
Named boolean gates
- •
const shouldRedact = !isOperator && requesterUserId;
- •
- •
Optional list entries
- •Example:
ts
const streamIds = ["all", `table:${id}`, handId ? `hand:${handId}` : null].filter(Boolean);
- •Example:
- •
Action fanout helpers
- •Use a
switchwith helper functions that return flags (e.g.,{ resetActedSeats }) to reduce nested action logic.
- •Use a
- •
Publish helpers
- •Create a
publishTableAndLobbyhelper to avoid repeating state + lobby broadcasts.
- •Create a
Guardrails
- •Preserve error strings and error codes.
- •Avoid changing payload shapes or field naming.
- •Keep logging semantics (no new logs, no removed logs).