Skip to content

Commit

Permalink
🐛 Fix Either Apply implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
priestine committed Jul 6, 2020
1 parent 4b4f959 commit 84f868e
Showing 1 changed file with 6 additions and 23 deletions.
29 changes: 6 additions & 23 deletions src/utils/either.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { Thunk, Unary } from '../types/common-types'
import { isFunction } from './guards'

type Nullable<T> = T | null | undefined

Expand All @@ -10,6 +9,7 @@ export interface IEitherStatic {
fromNullable: <TContext>(x: Nullable<TContext>) => IEither<NonNullable<TContext>, null>
right: <TContext, TLeftContext = TContext>(x: TContext) => IEither<TContext, TLeftContext>
left: <TContext, TRightContext = TContext>(x: TContext) => IEither<TRightContext, TContext>
of: <TContext, TLeftContext = TContext>(x: TContext) => IEither<TContext, TLeftContext>
}

export interface IEither<TRightContext, TLeftContext = TRightContext> {
Expand All @@ -30,15 +30,9 @@ export interface IEither<TRightContext, TLeftContext = TRightContext> {
leftChain: <TNewContext>(
onLeft: (ctx: TLeftContext) => IEither<TRightContext, TNewContext>,
) => IEither<TRightContext, TNewContext>
ap: <TNewContext>(
other: IEither<
TNewContext extends Unary<TRightContext>
? TNewContext
: TRightContext extends Unary<TNewContext>
? TNewContext
: never
>,
) => IEither<TNewContext, TLeftContext>
ap: <TNewRight, TNewLeft = TLeftContext>(
other: IEither<Unary<TRightContext, TNewRight>, Unary<TRightContext, TNewLeft>>,
) => IEither<TNewRight, TLeftContext>
swap: () => IEither<TLeftContext, TRightContext>
chain: <TNewContext, TFail>(
onRight: (ctx: TRightContext) => IEither<TNewContext, TFail>,
Expand Down Expand Up @@ -76,19 +70,7 @@ export const right = <TContext>(x: TContext): IEither<TContext> => ({
leftMap: () => right(x) as any,
leftChain: () => right(x) as any,
swap: () => left(x),
ap: (other) => {
const y: any = other.fold(
() => undefined,
(x) => x,
)
const isFunctionX = isFunction(x)

if (!isFunctionX && !isFunction(y)) {
throw new TypeError('At least one of the Eithers must hold a function to allow io.ap.')
}

return isFunctionX ? other.map(x as any) : right(y(x))
},
ap: (other) => (other.isRight ? (right(other[unsafeGet]()(x)) as any) : right(x)),
chain: (f) => f(x) as any,
fold: (_, onRight) => onRight(x),
})
Expand All @@ -104,4 +86,5 @@ export const Either: IEitherStatic = {
fromNullable: (x) => (x == null ? left(null) : (right(x) as any)),
right: (x) => right(x) as any,
left: (x) => left(x),
of: (x) => right(x) as any,
}

0 comments on commit 84f868e

Please sign in to comment.