Created
June 25, 2025 16:36
-
-
Save dmurawsky/b41a1400f675d765981511d691fb4b75 to your computer and use it in GitHub Desktop.
A ledger system for event sourcing in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export type TimeLedgerItem = { | |
| amountPerMs: number; | |
| /** The timestamp of when the ledger item was ended */ | |
| endedAt?: number; | |
| }; | |
| export type SumLedgerItem = { | |
| /** If the resource has been stored, this will tell you where */ | |
| storageMapContentPath?: string; | |
| amount: number; | |
| }; | |
| /** Type guard for checking if a ledger item is a TimeLedgerItem */ | |
| export const isTimeLedgerItem = (item: TimeLedgerItem | SumLedgerItem): item is TimeLedgerItem => "amountPerMs" in item; | |
| export function ledgerAccumulator(currentTimestamp: number) { | |
| return (acc: number, [timestamp, ledgerItem]: [string, TimeLedgerItem | SumLedgerItem]) => { | |
| let amount = 0; | |
| if (isTimeLedgerItem(ledgerItem)) { | |
| amount = | |
| ledgerItem.amountPerMs * | |
| // endedAt could be in the future because we calculate it based on capacity | |
| // so we use the current time if enededAt is in the future | |
| ((ledgerItem.endedAt ? Math.min(Date.now(), ledgerItem.endedAt) : currentTimestamp) - Number(timestamp)); | |
| } else { | |
| amount = ledgerItem.amount; | |
| } | |
| return acc + amount; | |
| }; | |
| } | |
| export function getLedgerTotal(ledger: Record<string, TimeLedgerItem | SumLedgerItem>, currentTimestamp = Date.now()) { | |
| return Object.entries(ledger).reduce(ledgerAccumulator(currentTimestamp), 0); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment