Skip to content

Commit

Permalink
feat: flatMapTaskOption
Browse files Browse the repository at this point in the history
  • Loading branch information
sukovanej committed May 23, 2023
1 parent e67ba03 commit b811e0f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/TaskEither.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,9 +398,11 @@ export const fromTaskOptionK = <E>(
}

/**
* Use `flatMapTaskOption`.
*
* The `W` suffix (short for **W**idening) means that the error types will be merged.
*
* @category sequencing
* @category legacy
* @since 2.12.3
*/
export const chainTaskOptionKW =
Expand All @@ -410,7 +412,9 @@ export const chainTaskOptionKW =
flatMap(ma, fromTaskOptionK<E1 | E2>(onNone)(f))

/**
* @category sequencing
* Use `flatMapTaskOption`.
*
* @category legacy
* @since 2.11.0
*/
export const chainTaskOptionK: <E>(
Expand Down Expand Up @@ -1254,6 +1258,19 @@ export const flatMapIOEither: {
flatMap(self, fromIOEitherK(f))
)

/**
* @category sequencing
* @since 2.16.0
*/
export const flatMapTaskOption: {
<A, E2, B>(f: (a: A) => TaskOption<B>, onNone: (a: A) => E2): <E1>(self: TaskEither<E1, A>) => TaskEither<E1 | E2, B>
<E1, A, E2, B>(self: TaskEither<E1, A>, f: (a: A) => TaskOption<B>, onNone: (a: A) => E2): TaskEither<E1 | E2, B>
} = /*#__PURE__*/ dual(
3,
<E1, A, E2, B>(self: TaskEither<E1, A>, f: (a: A) => TaskOption<B>, onNone: (a: A) => E2): TaskEither<E1 | E2, B> =>
flatMap(self, (a) => fromTaskOption(() => onNone(a))(f(a)))
)

/**
* Alias of `flatMapEither`.
*
Expand Down
10 changes: 10 additions & 0 deletions test/TaskEither.ts
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,16 @@ describe.concurrent('TaskEither', () => {
U.deepStrictEqual(await pipe(_.left('b'), f)(), E.left('b'))
})

it('flatMapTaskOption', async () => {
const f = _.flatMapTaskOption(
(n: number) => (n > 0 ? TO.some(n * 2) : TO.none),
() => 'a'
)
U.deepStrictEqual(await pipe(_.right(1), f)(), E.right(2))
U.deepStrictEqual(await pipe(_.right(-1), f)(), E.left('a'))
U.deepStrictEqual(await pipe(_.left('b'), f)(), E.left('b'))
})

it('tapIO', async () => {
const ref: Array<number> = []
const add = (value: number) => () => ref.push(value)
Expand Down

0 comments on commit b811e0f

Please sign in to comment.