/** * Either: the result of an operation that can fail, without exceptions (template from the `dev` skill). * Left holds the error, Right holds the value. Lives in `shared` so the domain can use it. */ export interface Left { readonly ok: false readonly error: L } export interface Right { readonly ok: true readonly value: R } export type Either = Left | Right export const left = (error: L): Left => ({ ok: false, error }) export function right(): Right export function right(value: R): Right export function right(value?: R): Right { return { ok: true, value } } export const isLeft = (result: Either): result is Left => !result.ok export const isRight = (result: Either): result is Right => result.ok export const map = (result: Either, transform: (value: R) => T): Either => result.ok ? right(transform(result.value)) : result export const flatMap = (result: Either, next: (value: R) => Either): Either => result.ok ? next(result.value) : result /** Collects every Right or returns the first Left (e.g. validating a list of items). */ export function all(results: ReadonlyArray>): Either { const values: R[] = [] for (const result of results) { if (!result.ok) return result values.push(result.value) } return right(values) }