Skip to content

Commit

Permalink
feat: add "recover" method
Browse files Browse the repository at this point in the history
closes #12
  • Loading branch information
raveclassic committed Sep 25, 2018
1 parent 9208e98 commit 26eb849
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/__tests__/remote-data.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -719,5 +719,20 @@ describe('RemoteData', () => {
expect(success(1).exists(p)).toBe(true);
});
});
describe('recover', () => {
const f = (error: string) => (error === 'foo' ? some(1) : none);
it('initial', () => {
expect(initialRD.recover(f)).toBe(initialRD);
});
it('pending', () => {
expect(pendingRD.recover(f)).toBe(pendingRD);
});
it('failure', () => {
expect(failure<string, number>('foo').recover(f)).toEqual(success(1));
});
it('success', () => {
expect(successRD.recover(f)).toBe(successRD);
});
});
});
});
28 changes: 28 additions & 0 deletions src/remote-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,13 @@ export class RemoteInitial<L, A> {
exists(p: Predicate<A>): boolean {
return false;
}

/**
* Processes failure error into new RemoteData if function f return some value
*/
recover(f: (error: L) => Option<A>): RemoteData<L, A> {
return this;
}
}

export class RemoteFailure<L, A> {
Expand Down Expand Up @@ -633,6 +640,13 @@ export class RemoteFailure<L, A> {
exists(p: Predicate<A>): boolean {
return false;
}

/**
* Processes failure error into new RemoteData if function f return some value
*/
recover(f: (error: L) => Option<A>): RemoteData<L, A> {
return f(this.error).fold<RemoteData<L, A>>(this, success);
}
}

export class RemoteSuccess<L, A> {
Expand Down Expand Up @@ -919,6 +933,13 @@ export class RemoteSuccess<L, A> {
exists(p: Predicate<A>): boolean {
return p(this.value);
}

/**
* Processes failure error into new RemoteData if function f return some value
*/
recover(f: (error: L) => Option<A>): RemoteData<L, A> {
return this;
}
}

export class RemotePending<L, A> {
Expand Down Expand Up @@ -1210,6 +1231,13 @@ export class RemotePending<L, A> {
exists(p: Predicate<A>): boolean {
return false;
}

/**
* Processes failure error into new RemoteData if function f return some value
*/
recover(f: (error: L) => Option<A>): RemoteData<L, A> {
return this;
}
}

/**
Expand Down

0 comments on commit 26eb849

Please sign in to comment.