Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 42 lines · 1.6 KiB · at 9472e3c

// Bug: truthiness checks (`!amountCents`, `!accounts[id]`) and in-place mutation of the input accounts.export type Account = { balanceCents: number; frozen: boolean };export type TransferFailure =  | { kind: "invalid_amount" }  | { kind: "same_account" }  | { kind: "unknown_account"; id: string }  | { kind: "frozen"; id: string }  | { kind: "insufficient_funds"; id: string; balanceCents: number; amountCents: number };export class TransferError extends Error {  declare readonly kind: TransferFailure["kind"];  declare readonly id?: string;  declare readonly balanceCents?: number;  declare readonly amountCents?: number;  constructor(failure: TransferFailure) {    super(failure.kind);    Object.assign(this, failure);  }}export function transfer(  accounts: Record<string, Account>,  from: string,  to: string,  amountCents: number,): Record<string, Account> {  if (!amountCents || amountCents < 0) throw new TransferError({ kind: "invalid_amount" });  if (from === to) throw new TransferError({ kind: "same_account" });  const src = accounts[from];  if (!src) throw new TransferError({ kind: "unknown_account", id: from });  const dst = accounts[to];  if (!dst) throw new TransferError({ kind: "unknown_account", id: to });  if (src.frozen) throw new TransferError({ kind: "frozen", id: from });  if (dst.frozen) throw new TransferError({ kind: "frozen", id: to });  if (src.balanceCents < amountCents) {    throw new TransferError({ kind: "insufficient_funds", id: from, balanceCents: src.balanceCents, amountCents });  }  src.balanceCents -= amountCents;  dst.balanceCents += amountCents;  return { ...accounts };}