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

splitMap - added targets field #336

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
117 changes: 113 additions & 4 deletions src/split-map/index.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,145 @@
import { Event, is, Store, Unit } from 'effector';
import { Event, Tuple, Unit, UnitTargetable, is, sample } from 'effector';

type TargetUnits<T> =
| UnitTargetable<T | void>
| Tuple<UnitTargetable<T | void>>
| ReadonlyArray<UnitTargetable<T | void>>;

const hasPropBase = {}.hasOwnProperty;
const hasOwnProp = <O extends { [k: string]: unknown }>(object: O, key: string) =>
hasPropBase.call(object, key);

/**
* Split `source` unit into multiple events based on the provided `cases`.
*
* @param source - Source unit, data from this unit is passed to each function in cases object and `__` event in shape as is
* @param cases - Object of functions. Function receives one argument is a payload from `source`, should return any value or `undefined`.
* If `undefined` is returned from the case function, update will be skipped (the event will not be triggered).
*
* @param targets (optional) - Object of units to trigger on corresponding event from cases object
* @returns Object of events, with the same structure as `cases`, but with the default event `__`, that will be triggered when each other function returns `undefined`
*
* @example
* ```ts
* const dataFetched = createEvent<unknown>()
*
* const dataReceived = splitMap({
* source: dataFetched,
* cases: {
* isString: (payload) => {
* if (typeof payload === 'string') return payload
* },
* isNumber: (payload) => {
* if (typeof payload === 'number') return payload
* },
* }
* })

* dataReceived.isString // Event<string>
* dataReceived.isNumber // Event<number>
* dataReceived.__ // Event<unknown>
* ```
*
* @example
* ```ts
* const dataFetched = createEvent<unknown>()
* const stringReceived = createEvent<string>()
* const numberReceived = createEvent<number>()
* const unknownReceived = createEvent<unknown>()
* const notifyError = createEvent()
*
* const dataReceived = splitMap({
* source: dataFetched,
* cases: {
* isString: (payload) => {
* if (typeof payload === 'string') return payload
* },
* isNumber: (payload) => {
* if (typeof payload === 'number') return payload
* },
* },
* targets: {
* isString: stringReceived,
* isNumber: numberReceived,
* __: [unknownReceived, notifyError],
* },
* })
*
* dataFetched('string')
* // => stringReceived('string')
*
* dataFetched(42)
* // => numberReceived(42)
*
* dataFetched(null)
* // => unknownReceived(null)
* // => notifyError()
* ```
*/

export function splitMap<
S,
Cases extends Record<string, (payload: S) => any | undefined>,
Targets extends {
[K in keyof Cases]?: Cases[K] extends (s: S) => infer R
? Targets[K] extends TargetUnits<infer TargetType>
? Exclude<R, undefined> extends TargetType
? TargetUnits<TargetType>
: TargetUnits<Exclude<R, undefined>>
: TargetUnits<Exclude<R, undefined>>
: never;
} & { __?: TargetUnits<S> },
>({
source,
cases,
targets,
}: {
source: Unit<S>;
cases: Cases;
targets?: Targets;
}): {
[K in keyof Cases]: Cases[K] extends (p: S) => infer R
? Event<Exclude<R, undefined>>
: never;
} & { __: Event<S> } {
const result: Record<string, Event<any> | Store<any>> = {};
const result: Record<string, Event<any>> = {};

let current = is.store(source) ? source.updates : (source as Event<S>);

for (const key in cases) {
if (key in cases) {
if (hasOwnProp(cases, key)) {
const fn = cases[key];

result[key] = current.filterMap(fn);
const caseEvent = current.filterMap(fn);

result[key] = caseEvent;

current = current.filter({
fn: (data) => !fn(data),
});

if (targets && hasOwnProp(targets, key)) {
const currentTarget = targets[key];

sample({
clock: caseEvent,
target: currentTarget as UnitTargetable<any>,
});
}
}
}

// eslint-disable-next-line no-underscore-dangle
result.__ = current;

if (targets && hasOwnProp(targets, '__')) {
const defaultCaseTarget = targets.__;

sample({
clock: current,
target: defaultCaseTarget as UnitTargetable<any>,
});
}

return result as any;
}
117 changes: 117 additions & 0 deletions src/split-map/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,120 @@ websocketEventReceived({ type: 'increment', name: 'demo', count: 5 });
websocketEventReceived({ type: 'bang', random: 'unknown' });
// => Unknown type: 'bang'
```

## `splitMap({ source, cases, targets? })`

### Motivation

Often we need the same behavior as in split — react to derived events received from `cases` and trigger the corresponding units. In `targets` field we can pass object with the same keys as in `cases` and values with `units` to trigger on the corresponding event.

### Formulae

```ts
splitMap({ source, cases, targets });
```

- On each `source` trigger, call each function in `cases` object one after another until function returns non undefined, and call event in `shape` with the same name as function in `cases` object.
- Trigger the corresponding `unit`(s) from `targets` object
- If no function returned value, event `__` in `shape` should be triggered, same for `targets` field — trigger `unit`(s) provided in `__` key

### Arguments

1. `source` ([_`Event`_] | [_`Store`_] | [_`Effect`_]) — Source unit, data from this unit passed to each function in `cases` object and `__` event in `shape` as is
2. `cases` (`{ [key: string]: (payload: T) => any | void }`) — Object of functions. Function receives one argument is a payload from `source`, should return any value or `undefined`
3. `targets` (`{ [key: string]?: Unit<any> | Unit<any>[]; __?: Unit<any> | Unit<any>[] }`) — Object of units to trigger on corresponding event from `cases` object

### Returns

- `shape` (`{ [key: string]: Event<any>; __: Event<T> }`) — Object of events, with the same structure as `cases`, but with the _default_ event `__`, that will be triggered when each other function returns `undefined`

[_`event`_]: https://effector.dev/docs/api/effector/event
[_`effect`_]: https://effector.dev/docs/api/effector/effect
[_`store`_]: https://effector.dev/docs/api/effector/store

### Examples

#### Split WebSocket events to effector events with targets

```ts
import { createEvent } from 'effector';
import { splitMap } from 'patronum/split-map';
import { spread } from 'patronum/spread';

type WSEvent =
| { type: 'init'; key: string }
| { type: 'increment'; count: number }
| { type: 'reset' };

export const websocketEventReceived = createEvent<WSEvent>();
const notifyError = createEvent();

const $isInitialized = createStore(false);
const $count = createStore<number | null>(null);

const getInitialDataFx = createEffect<string, void>();

splitMap({
source: websocketEventReceived,
cases: {
init: (event) => {
if (event.type === 'init') return { init: true, dataId: event.key };
},
increment: (payload) => {
if (payload.type === 'increment') return payload.count;
},
reset: ({ type }) => {
if (type === 'reset') return null;
},
},
targets: {
// EventCallable<{ init?: boolean; dataId?: string }>
init: spread({ init: $isInitialized, dataId: getInitialDataFx }),
increment: $count,
reset: [$count.reinit, $isInitialized.reinit],
__: notifyError,
},
});

websocketEventReceived({ type: 'init', key: 'key' });
// => $isInitialized: true, getInitialDataFx: 'key'

websocketEventReceived({ type: 'increment', count: 2 });
// => $count: 2

websocketEventReceived({ type: 'reset' });
// => $count: null, $isInitialized: false
```

#### We can still use returned events to do some other logic

```ts
const { init } = splitMap({
source: websocketEventReceived,
cases: {
init: (event) => {
if (event.type === 'init') return { init: true, dataId: event.key };
},
increment: (payload) => {
if (payload.type === 'increment') return payload.count;
},
reset: ({ type }) => {
if (type === 'reset') return null;
},
},
targets: {
// EventCallable<{ init?: boolean; dataId?: string }>
init: spread({ init: $isInitialized, dataId: getInitialDataFx }),
increment: $count,
reset: [$count.reinit, $isInitialized.reinit],
},
});

sample({
clock: init,
// some other logic
source: ...,
filter: ...,
target: ...,
})
```
Loading
Loading