Skip to content

Commit

Permalink
feat: add skip & take
Browse files Browse the repository at this point in the history
  • Loading branch information
rokashkovvd committed Oct 10, 2024
1 parent 150c823 commit a68f6eb
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/skip/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Event, Store, Unit, createEvent, createStore, is, sample } from 'effector';

export function skip<T>({
clock,
count,
reset,
}: {
clock: Unit<T>;
count: Store<number> | number;
reset?: Unit<T>;
}): Event<T> {
const $count = is.store(count) ? count : createStore(count);

const $skipped = createStore(0);

reset = is.unit(reset) ? reset : createEvent();

const $canTrigger = sample({
source: [$skipped, $count],
fn: ([skp, cnt]) => skp >= cnt,
});

const event = sample({
clock,
source: $skipped,
filter: $canTrigger,
fn: (_, params) => params,
});

sample({
clock,
source: $skipped,
filter: $canTrigger.map((can) => !can),
fn: (skp) => skp + 1,
target: $skipped,
});

sample({
clock: [$count, reset],
target: $skipped.reinit,
});

return event;
}
44 changes: 44 additions & 0 deletions src/take/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Event, Store, Unit, createEvent, createStore, is, sample } from 'effector';

export function skip<T>({
clock,
count,
reset,
}: {
clock: Unit<T>;
count: Store<number> | number;
reset?: Unit<T>;
}): Event<T> {
const $count = is.store(count) ? count : createStore(count);

const $skipped = createStore(0);

reset = is.unit(reset) ? reset : createEvent();

const $canTrigger = sample({
source: [$skipped, $count],
fn: ([skp, cnt]) => skp >= cnt,
});

const event = sample({
clock,
source: $skipped,
filter: $canTrigger,
fn: (_, params) => params,
});

sample({
clock,
source: $skipped,
filter: $canTrigger.map((can) => !can),
fn: (skp) => skp + 1,
target: $skipped,
});

sample({
clock: [$count, reset],
target: $skipped.reinit,
});

return event;
}

0 comments on commit a68f6eb

Please sign in to comment.