import { Actual } from "base/Actual"; import { DestroyContainer } from "base/DestroyContainer"; import { Message } from "base/Message"; import { isMessage } from "helpers/guards"; import { ConstructorType } from "types/ConstructorType"; import { MaybeMessage } from "types/MessageType"; /** * An message that applies a function * to the value of the base message * * @url https://silentium.pw/article/applied/view */ export function Applied( base: MaybeMessage, applier: ConstructorType<[T], MaybeMessage>, ) { const $base = Actual(base); return Message(function AppliedImpl(resolve, reject) { const dc = DestroyContainer(); $base.catch(reject); $base.then(function appliedBaseSub(v) { const result = applier(v); if (isMessage(result)) { dc.destroy(); dc.add(result); result.catch(reject).then(resolve); } else { resolve(result); } }); }); }