import type { Mapper, SideEffect } from "@emprespresso/pengueno"; // the "thing" every Trace writer must "trace()" type BaseTraceWith = string; export type ITraceWith = BaseTraceWith | T; export interface ITrace { addTrace: Mapper, ITrace>; trace: SideEffect>; } export type ITraceableTuple = [T, BaseTraceWith | TraceWith]; export type ITraceableMapper< T, U, TraceWith, W = ITraceable, > = ( w: W, ) => U; export interface ITraceable { readonly item: T; readonly trace: ITrace; move(u: U): ITraceable; map: ( mapper: ITraceableMapper, ) => ITraceable; bimap: ( mapper: ITraceableMapper, Trace>, ) => ITraceable; peek: (peek: ITraceableMapper) => ITraceable; flatMap: ( mapper: ITraceableMapper, Trace>, ) => ITraceable; flatMapAsync( mapper: ITraceableMapper>, Trace>, ): ITraceable, Trace>; } export class TraceableImpl implements ITraceable { protected constructor( readonly item: T, readonly trace: ITrace, ) {} public map( mapper: ITraceableMapper, ) { const result = mapper(this); return new TraceableImpl(result, this.trace); } public flatMap( mapper: ITraceableMapper< T, ITraceable, TraceWith >, ): ITraceable { return mapper(this); } public flatMapAsync( mapper: ITraceableMapper< T, Promise>, TraceWith >, ): ITraceable, TraceWith> { return new TraceableImpl( mapper(this).then(({ item }) => item), this.trace, ); } public peek(peek: ITraceableMapper) { peek(this); return this; } public move(t: Tt): ITraceable { return this.map(() => t); } public bimap( mapper: ITraceableMapper< T, ITraceableTuple, TraceWith >, ) { const [item, trace] = mapper(this); return new TraceableImpl(item, this.trace.addTrace(trace)); } }