Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement basic interval method #163

Merged
merged 3 commits into from
Oct 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
- [Debounce](#debounce) — Creates event which waits until time passes after previous trigger.
- [Delay](#delay) — Delays the call of the event by defined timeout.
- [Throttle](#throttle) — Creates event which triggers at most once per timeout.
- [Interval](#interval) — Creates a dynamic interval with any timeout.

### Combination/Decomposition

Expand Down Expand Up @@ -185,6 +186,34 @@ trigger(4);

[Try it](https://share.effector.dev/OH0TUJUH)

## Interval

[Method documentation & API](/src/interval)

```ts
import { createStore, createEvent } from 'effector'
import { interval } from 'patronum'

const startCounter = createEvent();
const stopCounter = createEvent();
const $counter = createStore(0);

const { tick } = interval({
timeout: 500,
start: startCounter,
stop: stopCounter
});

$counter.on(tick, (number) => number + 1);
$counter.watch(value => console.log("COUNTER", value));

startCounter();

setTimeout(() => stopCounter(), 5000)
```

[Try it](https://share.effector.dev/EOVzc3df)

## Debug

[Method documentation & API](/src/debug)
Expand Down
103 changes: 103 additions & 0 deletions src/interval/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import {
Event,
Store,
createEvent,
createEffect,
createStore,
guard,
sample,
is,
} from 'effector';

export function interval<S extends unknown, F extends unknown>({
timeout,
start,
stop,
leading = false,
trailing = false,
}: {
timeout: number | Store<number>;
start: Event<S>;
stop?: Event<F>;
leading?: boolean;
trailing?: boolean;
}): { tick: Event<void>; isRunning: Store<boolean> } {
const tick = createEvent();
const $isRunning = createStore(false);
const $timeout = toStoreNumber(timeout);

const $notRunning = $isRunning.map((running) => !running);

let timeoutId: NodeJS.Timeout;

const timeoutFx = createEffect<number, void>((timeout) => {
return new Promise((resolve) => {
timeoutId = setTimeout(resolve, timeout);
});
});

const cleanupFx = createEffect(() => {
clearTimeout(timeoutId);
});

guard({
clock: start,
source: $timeout,
filter: $notRunning,
target: timeoutFx,
});

if (leading) {
guard({
clock: start,
filter: $notRunning,
target: tick,
});
}

sample({
clock: start,
fn: () => true,
target: $isRunning,
});

guard({
clock: timeoutFx.done,
source: $timeout,
filter: $isRunning,
target: timeoutFx,
});

sample({
clock: timeoutFx.done,
fn: () => {
/* to be sure, nothing passed to tick */
},
target: tick,
});

if (stop) {
if (trailing) {
sample({
clock: stop,
target: tick,
});
}

$isRunning.on(stop, () => false);
sample({ clock: stop, target: cleanupFx });
}

return { tick, isRunning: $isRunning };
}

function toStoreNumber(value: number | Store<number> | unknown): Store<number> {
if (is.store(value)) return value;
if (typeof value === 'number') {
return createStore(value, { name: '$timeout' });
}

throw new TypeError(
`timeout parameter in interval method should be number or Store. "${typeof value}" was passed`,
);
}
80 changes: 80 additions & 0 deletions src/interval/interval.fork.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { allSettled, createEvent, fork } from 'effector';
import { argumentHistory, wait, watch } from '../../test-library';
import { interval } from '.';

test('works in forked scope', async () => {
const start = createEvent();
const stop = createEvent();
const { tick } = interval({ timeout: 10, start, stop });
const fn = watch(tick);

const scope = fork();
allSettled(start, { scope });
expect(fn).not.toBeCalled();

await wait(30);
expect(fn).toBeCalledTimes(2);

allSettled(stop, { scope });

await wait(30);
expect(fn).toBeCalledTimes(2);
});

test('isRunning works in fork', async () => {
const start = createEvent();
const stop = createEvent();
const { tick, isRunning } = interval({ timeout: 10, start, stop });
const fn = watch(isRunning);

const scope = fork();
expect(scope.getState(isRunning)).toBe(false);

allSettled(start, { scope });
expect(scope.getState(isRunning)).toBe(true);

await wait(30);
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
false,
true,
]
`);

allSettled(stop, { scope });

await wait(30);
expect(argumentHistory(fn)).toMatchInlineSnapshot(`
Array [
false,
true,
false,
]
`);
});

test('concurrent run of interval in different scopes', async () => {
const start = createEvent();
const stop = createEvent();
const { tick, isRunning } = interval({ timeout: 10, start, stop });
const fn = watch(isRunning);

const scopeA = fork();
const scopeB = fork();

allSettled(start, { scope: scopeA });
expect(scopeA.getState(isRunning)).toBe(true);
expect(scopeB.getState(isRunning)).toBe(false);

allSettled(start, { scope: scopeB });
expect(scopeA.getState(isRunning)).toBe(true);
expect(scopeB.getState(isRunning)).toBe(true);

allSettled(stop, { scope: scopeB });
expect(scopeA.getState(isRunning)).toBe(true);
expect(scopeB.getState(isRunning)).toBe(false);

allSettled(stop, { scope: scopeA });
expect(scopeA.getState(isRunning)).toBe(false);
expect(scopeB.getState(isRunning)).toBe(false);
});
Loading