Skip to content

Commit 5c26c11

Browse files
authored
feat: add Fold 3 (#53)
closes #30
1 parent cf76eab commit 5c26c11

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/__tests__/remote-data.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -648,6 +648,20 @@ describe('RemoteData', () => {
648648
expect(RD.fold(() => 1, () => 2, () => 3, () => 4)(successRD)).toBe(4);
649649
});
650650
});
651+
describe('fold3', () => {
652+
it('initial', () => {
653+
expect(RD.fold3(() => 1, () => 2, () => 3)(initialRD)).toBe(1);
654+
});
655+
it('pending', () => {
656+
expect(RD.fold3(() => 1, () => 2, () => 3)(pendingRD)).toBe(1);
657+
});
658+
it('failure', () => {
659+
expect(RD.fold3(() => 1, () => 2, () => 3)(failureRD)).toBe(2);
660+
});
661+
it('success', () => {
662+
expect(RD.fold3(() => 1, () => 2, () => 3)(successRD)).toBe(3);
663+
});
664+
});
651665
describe('isInitial', () => {
652666
it('initial', () => {
653667
expect(isInitial(initialRD)).toBe(true);

src/remote-data.ts

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,8 @@ export const getOrElse = <L, A>(f: Lazy<A>) => (ma: RemoteData<L, A>): A => (isS
127127
* It applies a function to each case in the data structure.
128128
*
129129
* @example
130-
* const onInitial = "it's initial"
131-
* const onPending = "it's pending"
130+
* const onInitial = () => "it's initial"
131+
* const onPending = () => "it's pending"
132132
* const onFailure = (err) => "it's failure"
133133
* const onSuccess = (data) => `${data + 1}`
134134
* const f = fold(onInitial, onPending, onFailure, onSuccess)
@@ -160,6 +160,28 @@ export const fold = <E, A, B>(
160160
}
161161
};
162162

163+
/**
164+
* A more concise way to "unwrap" values from {@link RemoteData} "container".
165+
* It uses fold in its implementation, collapsing `onInitial` and `onPending` on the `onNone` handler.
166+
* When fold's `onInitial` returns, `onNode` is called with `none`.
167+
*
168+
* @example
169+
* const onNone = (progressOption) => "no data to show"
170+
* const onFailure = (err) => "sorry, the request failed"
171+
* const onSuccess = (data) => `result is: ${data + 1}`
172+
* const f = fold(onInitial, onPending, onFailure, onSuccess)
173+
*
174+
* f(initial) // "no data to show"
175+
* f(pending) // "no data to show"
176+
* f(failure(new Error('error text'))) // "sorry, the request failed"
177+
* f(success(21)) // "result is: 22"
178+
*/
179+
export const fold3 = <E, A, R>(
180+
onNone: (progress: Option<RemoteProgress>) => R,
181+
onFailure: (e: E) => R,
182+
onSuccess: (a: A) => R,
183+
): ((fa: RemoteData<E, A>) => R) => fold(() => onNone(none), onNone, onFailure, onSuccess);
184+
163185
/**
164186
* One more way to fold (unwrap) value from {@link RemoteData}.
165187
* `Left` part will return `null`.

0 commit comments

Comments
 (0)