Skip to content

Commit

Permalink
feat: exists
Browse files Browse the repository at this point in the history
  • Loading branch information
Hfutsora committed May 23, 2022
1 parent ea23c46 commit 75c5053
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/Either.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,15 @@ export const chain = <E2, A, B>(f: (a: A) => Either<E2, B>) => <E1>(ma: Either<E
*/
export const orElse = <E1, E2, B>(onLeft: (e: E1) => Either<E2, B>) => <A>(ma: Either<E1, A>): Either<E2, A | B> =>
isLeft(ma) ? onLeft(ma.left) : ma

/**
* Returns `false` if `Either` is a `Left`, otherwise returns the predicate result.
*
* @example
*
* assert.deepStrictEqual(exists((n: number) => n > 0)(left(0)), false)
* assert.deepStrictEqual(exists((n: number) => n > 0)(right(0)), false)
* assert.deepStrictEqual(exists((n: number) => n > 0)(right(1)), true)
*/
export const exists = <A>(predicate: Predicate<A>) => <E>(ma: Either<E, A>): boolean =>
isLeft(ma) ? false : predicate(ma.right)
8 changes: 7 additions & 1 deletion test/Either.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isLeft, left, right, isRight, map, of, fromPredicate, match, getOrElse, chain, orElse } from '../src/Either'
import { isLeft, left, right, isRight, map, of, fromPredicate, match, getOrElse, chain, orElse, exists } from '../src/Either'

test('isLeft', () => {
expect(isLeft(left(0))).toBeTruthy()
Expand Down Expand Up @@ -49,3 +49,9 @@ test('orElse', () => {
expect(orElse((n: number) => right(n + 1))(left(1))).toEqual(right(2))
expect(orElse((n: number) => right(n + 1))(right(1))).toEqual(right(1))
})

test('exists', () => {
expect(exists((n: number) => n > 0)(left(0))).toBeFalsy()
expect(exists((n: number) => n > 0)(right(0))).toBeFalsy()
expect(exists((n: number) => n > 0)(right(1))).toBeTruthy()
})

0 comments on commit 75c5053

Please sign in to comment.