import type { Mapper, SideEffect, Supplier } 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 trace: ITrace; get: Supplier; move: (u: U) => ITraceable; map: ( mapper: ITraceableMapper, ) => ITraceable; bimap: ( mapper: ITraceableMapper< T, ITraceableTuple | Trace>, Trace >, ) => ITraceable; peek: (peek: ITraceableMapper) => ITraceable; flatMap: ( mapper: ITraceableMapper, Trace>, ) => ITraceable; flatMapAsync( mapper: ITraceableMapper>, Trace>, ): ITraceable, Trace>; } export class TraceableImpl implements ITraceable { protected constructor( private readonly item: T, public 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((t) => t.get()), 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>, TraceWith >, ) { const [item, trace] = mapper(this); const traces = Array.isArray(trace) ? trace : [trace]; return new TraceableImpl( item, traces.reduce((trace, _trace) => trace.addTrace(_trace), this.trace), ); } public get() { return this.item; } }