From 7f8674a3bfe926b383ae920f22b73c227d5970ad Mon Sep 17 00:00:00 2001 From: velialiev Date: Thu, 16 May 2024 14:33:17 +0300 Subject: [PATCH] feat: add patronum defer --- src/defer/index.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/defer/index.ts diff --git a/src/defer/index.ts b/src/defer/index.ts new file mode 100644 index 00000000..aaf09588 --- /dev/null +++ b/src/defer/index.ts @@ -0,0 +1,30 @@ +import { Store, Unit, merge, sample } from 'effector'; +import { combineEvents } from '../combine-events'; +import { not } from '../not'; + +export interface DeferArgs { + clock: Unit; + until: Store; +} + +export const defer = (args: DeferArgs) => { + const { clock, until: condition } = args; + + const calledAfterCondition = sample({ + clock: clock, + filter: condition, + }); + + const calledBeforeCondition = sample({ + clock: clock, + filter: not(condition), + }); + + return merge([ + calledAfterCondition, + combineEvents({ + events: [calledBeforeCondition, condition.updates.filter({ fn: Boolean })], + reset: condition.updates.filter({ fn: (value) => !value }), + }), + ]); +};