Skip to content

Commit

Permalink
feat: add Fold 3 (#53)
Browse files Browse the repository at this point in the history
closes #30
  • Loading branch information
fes300 committed Dec 27, 2020
1 parent cf76eab commit 5c26c11
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
14 changes: 14 additions & 0 deletions src/__tests__/remote-data.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,20 @@ describe('RemoteData', () => {
expect(RD.fold(() => 1, () => 2, () => 3, () => 4)(successRD)).toBe(4);
});
});
describe('fold3', () => {
it('initial', () => {
expect(RD.fold3(() => 1, () => 2, () => 3)(initialRD)).toBe(1);
});
it('pending', () => {
expect(RD.fold3(() => 1, () => 2, () => 3)(pendingRD)).toBe(1);
});
it('failure', () => {
expect(RD.fold3(() => 1, () => 2, () => 3)(failureRD)).toBe(2);
});
it('success', () => {
expect(RD.fold3(() => 1, () => 2, () => 3)(successRD)).toBe(3);
});
});
describe('isInitial', () => {
it('initial', () => {
expect(isInitial(initialRD)).toBe(true);
Expand Down
26 changes: 24 additions & 2 deletions src/remote-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,8 @@ export const getOrElse = <L, A>(f: Lazy<A>) => (ma: RemoteData<L, A>): A => (isS
* It applies a function to each case in the data structure.
*
* @example
* const onInitial = "it's initial"
* const onPending = "it's pending"
* const onInitial = () => "it's initial"
* const onPending = () => "it's pending"
* const onFailure = (err) => "it's failure"
* const onSuccess = (data) => `${data + 1}`
* const f = fold(onInitial, onPending, onFailure, onSuccess)
Expand Down Expand Up @@ -160,6 +160,28 @@ export const fold = <E, A, B>(
}
};

/**
* A more concise way to "unwrap" values from {@link RemoteData} "container".
* It uses fold in its implementation, collapsing `onInitial` and `onPending` on the `onNone` handler.
* When fold's `onInitial` returns, `onNode` is called with `none`.
*
* @example
* const onNone = (progressOption) => "no data to show"
* const onFailure = (err) => "sorry, the request failed"
* const onSuccess = (data) => `result is: ${data + 1}`
* const f = fold(onInitial, onPending, onFailure, onSuccess)
*
* f(initial) // "no data to show"
* f(pending) // "no data to show"
* f(failure(new Error('error text'))) // "sorry, the request failed"
* f(success(21)) // "result is: 22"
*/
export const fold3 = <E, A, R>(
onNone: (progress: Option<RemoteProgress>) => R,
onFailure: (e: E) => R,
onSuccess: (a: A) => R,
): ((fa: RemoteData<E, A>) => R) => fold(() => onNone(none), onNone, onFailure, onSuccess);

/**
* One more way to fold (unwrap) value from {@link RemoteData}.
* `Left` part will return `null`.
Expand Down

0 comments on commit 5c26c11

Please sign in to comment.