Skip to content

Commit

Permalink
feat: add Task.prototype.failIf
Browse files Browse the repository at this point in the history
  • Loading branch information
tdreyno committed Jan 8, 2021
1 parent 7b91b37 commit 1ae3cc9
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Task/Task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,18 @@ export const retryWithExponentialBackoff = <E, S>(
export const flatten = <E, S>(task: Task<E, Task<E, S>>): Task<E, S> =>
task.chain(identity)

/**
* Given a predicate, if it returns true, error the task with a given value.
* @param pred Run this on a successful task, return true to fail the task.
* @param error If the predicate succeeded, run this function to get the error result.
*/
export const failIf = <E, S, E2>(
pred: (result: S) => boolean,
error: (result: S) => E2,
task: Task<E, S>,
): Task<E | E2, S> =>
task.chain(result => (pred(result) ? fail(error(result)) : of(result)))

/**
* Create a new task.
* @param computation A function which will be run when the task starts.
Expand Down Expand Up @@ -963,6 +975,13 @@ export class Task<E, S> implements PromiseLike<S> {
public flatten<S2>(this: Task<E, Task<E, S2>>): Task<E, S2> {
return flatten(this)
}

public failIf<E2>(
pred: (result: S) => boolean,
error: (result: S) => E2,
): Task<E | E2, S> {
return failIf(pred, error, this)
}
}

/**
Expand Down
31 changes: 31 additions & 0 deletions src/Task/__tests__/failIf.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { of } from "../Task"

describe("failIf", () => {
test("should fail with new error type", () => {
const resolve = jest.fn()
const reject = jest.fn()

const lt5 = (v: number) => v < 5

of(4)
.failIf(lt5, v => `${v} < 5`)
.fork(reject, resolve)

expect(resolve).not.toBeCalled()
expect(reject).toBeCalledWith("4 < 5")
})

test("should succeed if predicate fails", () => {
const resolve = jest.fn()
const reject = jest.fn()

const lt5 = (v: number) => v < 5

of(10)
.failIf(lt5, v => `${v} < 5`)
.fork(reject, resolve)

expect(reject).not.toBeCalled()
expect(resolve).toBeCalledWith(10)
})
})

0 comments on commit 1ae3cc9

Please sign in to comment.