Skip to content

Commit 7e2a755

Browse files
committed
feat: implement applyPar in effect.ts
1 parent a337e88 commit 7e2a755

2 files changed

Lines changed: 54 additions & 2 deletions

File tree

deno.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@baetheus/fun",
3-
"version": "3.0.0-rc.7",
3+
"version": "3.0.0-rc.8",
44
"exports": {
55
"./applicable": "./applicable.ts",
66
"./array": "./array.ts",

effect.ts

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,6 +559,58 @@ export function apply<A, B, S3 extends unknown[], S2 extends unknown[]>(
559559
};
560560
}
561561

562+
/**
563+
* Apply a function wrapped in an Effect to a value wrapped in an Effect.
564+
* Both Effects must succeed for the application to succeed. The function
565+
* Effect is executed first, then the value Effect. This function is limited to
566+
* state values that are invariant and immutable in order to achieve paralell
567+
* execution of the function and value parameters.
568+
*
569+
* @example
570+
* ```ts
571+
* import * as Eff from "./effect.ts";
572+
* import * as E from "./either.ts";
573+
* import { pipe } from "./fn.ts";
574+
*
575+
* const add = (a: number) => (b: number) => a + b;
576+
* const addEffect = Eff.right(add(5));
577+
* const valueEffect = Eff.right(10);
578+
*
579+
* const result = await pipe(
580+
* addEffect,
581+
* Eff.apply(valueEffect)
582+
* )("state");
583+
* // [Either.right(15), "state"]
584+
*
585+
* const errorResult = await pipe(
586+
* Eff.left("function error"),
587+
* Eff.apply(valueEffect)
588+
* )("state");
589+
* // [Either.left("function error"), "state"]
590+
* ```
591+
*
592+
* @since 2.3.5
593+
*/
594+
export function applyPar<A, B, S extends unknown[]>(
595+
ua: Effect<S, B, A, S>,
596+
): <I, J>(
597+
ufai: Effect<S, J, (a: A) => I | Promise<I>, S>,
598+
) => Effect<S, B | J, I, S> {
599+
return (ufai) => async (...s) => {
600+
const [[efai], [ea]] = await Promise.all(
601+
ufai.apply(ufai, s),
602+
ua.apply(ua, s),
603+
);
604+
if (Either.isLeft(efai)) {
605+
return [efai, ...s];
606+
}
607+
if (Either.isLeft(ea)) {
608+
return [ea, ...s];
609+
}
610+
return [Either.right(await efai.right(ea.right)), ...s];
611+
};
612+
}
613+
562614
/**
563615
* Chain Effects by applying a function that returns an Effect to the
564616
* success value of an Effect. This allows for sequential composition
@@ -1154,5 +1206,5 @@ export function bindTo<N extends string>(
11541206
export function getFlatmappableEffect<S extends unknown[]>(): Flatmappable<
11551207
KindEffectState<S>
11561208
> {
1157-
return { wrap, apply, map, flatmap };
1209+
return { wrap, apply: applyPar, map, flatmap };
11581210
}

0 commit comments

Comments
 (0)