Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Text · 45 lines · 1.9 KiB · at 503e839

import { Ok, Err, type Result } from "@tsus/runtime";export type Account = { balanceCents: number; frozen: boolean };export type TransferError =  | { kind: "invalid_amount" }  | { kind: "same_account" }  | { kind: "unknown_account"; id: string }  | { kind: "frozen"; id: string }  | { kind: "insufficient_funds"; id: string; balanceCents: number; amountCents: number };const lookup = (accounts: Record<string, Account>, id: string): Result<Account, TransferError> =>  Object.hasOwn(accounts, id) ? Ok(accounts[id]) : Err({ kind: "unknown_account", id });const notFrozen = (account: Account, id: string): Result<Account, TransferError> =>  account.frozen ? Err({ kind: "frozen", id }) : Ok(account);const checkAmount = (amountCents: number): Result<number, TransferError> =>  Number.isInteger(amountCents) && amountCents > 0 ? Ok(amountCents) : Err({ kind: "invalid_amount" });const distinct = (from: string, to: string): Result<string, TransferError> =>  from === to ? Err({ kind: "same_account" }) : Ok(to);export const transfer = (  accounts: Record<string, Account>,  from: string,  to: string,  amountCents: number,): Result<Record<string, Account>, TransferError> =>  checkAmount(amountCents)    .andThen(() => distinct(from, to))    .andThen(() => lookup(accounts, from))    .andThen((src) =>      lookup(accounts, to)        .andThen((dst) => notFrozen(src, from).andThen(() => notFrozen(dst, to)))        .andThen((dst): Result<Record<string, Account>, TransferError> =>          src.balanceCents < amountCents            ? Err({ kind: "insufficient_funds", id: from, balanceCents: src.balanceCents, amountCents })            : Ok({                ...accounts,                [from]: { ...src, balanceCents: src.balanceCents - amountCents },                [to]: { ...dst, balanceCents: dst.balanceCents + amountCents },              }),        ),    );