@b-jones-rfd/func-help - v0.7.1
    Preparing search index...

    Class Either<L, R>

    A value that is either a Left (typically an error) or a Right (a successful computation).

    Either<L, R> ≅ Left | Right

    Only the Right branch is considered for map/bind sequencing; the Left branch short‑circuits the chain.

    A throw in a caller-supplied function propagates synchronously from the call that ran it and is not captured as a Left; only tryCatch captures throws, and only from effect.

    import { Either } from '@b-jones-rfd/func-help'

    type Err = string

    const parseNumber = (s: string): Either<Err, number> => {
    const n = parseFloat(s)
    return isNaN(n) ? Either.left(`'${s}' is not a number`) : Either.right(n)
    }

    const reciprocal = (n: number): Either<Err, number> => {
    return n === 0 ? Either.left('division by zero') : Either.right(1 / n)
    }

    const program = parseNumber('10').bind(reciprocal)

    const result = program.fold(
    (err) => `Error: ${err}`,
    (value) => `Reciprocal is ${value}`
    )
    // result === 'Reciprocal is 0.1'

    Type Parameters

    • L

      Usually the error type.

    • R

      Usually the success value type.

    Implements

    Index
    • Let yield* bind this Either inside a do block: yields this Either and returns the Right value the block is resumed with.

      It exists for yield*, not for spreading: [...either] is a one-element array holding this Either itself.

      Returns Generator<Either<L, R>, R, unknown>

      A generator that yields this Either once.

      import { Either } from '@b-jones-rfd/func-help'

      Either.do(function* () {
      const n = yield* Either.right<number, string>(2) // calls this method
      return n * 2
      }) // Right(4)
    • Map both sides at once: onLeft for a Left, onRight for a Right. Only the function for this side is called. If the function called throws, the error propagates from this call; it is not captured as a Left.

      This is Haskell's bimap (Data.Bifunctor). x.bimap(f, g) is x.mapLeft(f).map(g).

      Type Parameters

      • L2

        The new Left type.

      • R2

        The new Right type.

      Parameters

      • onLeft: (l: L) => L2

        The function to apply to a Left value.

      • onRight: (r: R) => R2

        The function to apply to a Right value.

      Returns Either<L2, R2>

      A Left holding onLeft(value), or a Right holding onRight(value).

      import { Either } from '@b-jones-rfd/func-help'

      const describe = (e: Either<string, number>) =>
      e.bimap(
      (m) => new Error(m),
      (n) => `port ${n}`
      )

      describe(Either.right(80)) // Right('port 80')
      describe(Either.left('bad port')) // Left(Error('bad port'))
    • Chain a step that may itself fail; the first Left short-circuits. If f throws, the error propagates from this call; it is not captured as a Left (use tryCatch for that).

      This is Haskell's >>=. f must return the same Left type, so every step in a chain shares one error type.

      Type Parameters

      • B

        The new Right type.

      Parameters

      • f: (r: R) => Either<L, B>

        The next step, given the Right value.

      Returns Either<L, B>

      The Either f returns, or this Left.

      import { Either } from '@b-jones-rfd/func-help'

      const half = (n: number): Either<string, number> =>
      n % 2 === 0 ? Either.right(n / 2) : Either.left('odd')

      Either.right<number, string>(4).bind(half) // Right(2)
      Either.right<number, string>(3).bind(half) // Left('odd')
    • Recover from a Left: handler gets the Left value and its Either replaces this one. A Right passes through without calling handler. If handler throws, the error propagates from this call; it is not captured as a Left.

      This is Haskell's catchError (MonadError). The handler may change the Left type, but not the Right type: it returns Either<L2, R>.

      Type Parameters

      • L2

        The Left type after recovery.

      Parameters

      • handler: (l: L) => Either<L2, R>

        Given the Left value, returns the Either to use instead.

      Returns Either<L2, R>

      The Either handler returns, or this Right.

      import { Either } from '@b-jones-rfd/func-help'

      const withDefault = (e: Either<string, number>): Either<never, number> =>
      e.catchError(() => Either.right(8080))

      withDefault(Either.left('no port')) // Right(8080)
      withDefault(Either.right(80)) // Right(80)
    • Collapse the Either into one value by handling both branches. If onLeft or onRight throws, the error propagates from this call.

      This is Haskell's either, renamed after the common JavaScript name; the Left handler comes first, as in Haskell.

      Type Parameters

      • B

        The type both handlers return.

      Parameters

      • onLeft: (l: L) => B

        Handles the Left value.

      • onRight: (r: R) => B

        Handles the Right value.

      Returns B

      What the handler for this branch returns.

      import { Either } from '@b-jones-rfd/func-help'

      Either.left<string, number>('bad').fold(
      (e) => e.length,
      (n) => n
      ) // 3
    • Extract the Right value or provide a default derived from the Left. If fallback throws, the error propagates from this call.

      This is Haskell's fromRight, but it takes a function of the Left rather than a plain default, so the fallback can use the error and is only computed for a Left.

      Parameters

      • fallback: (l: L) => R

        Builds the value to return for a Left, given the Left.

      Returns R

      The Right value, or fallback(left).

      import { Either } from '@b-jones-rfd/func-help'

      Either.right<number, string>(3).getOrElse(() => 0) // 3
      Either.left<string, number>('bad').getOrElse((e) => e.length) // 3
    • Test whether this is a Left.

      It is a type guard, so the Right type narrows to never in the true branch.

      Returns this is Either<L, never>

      true if this is a Left.

      import { Either } from '@b-jones-rfd/func-help'

      Either.left('boom').isLeft() // true
      Either.of(1).isLeft() // false
    • Test whether this is a Right.

      It is a type guard, so the Left type narrows to never in the true branch.

      Returns this is Either<never, R>

      true if this is a Right.

      import { Either } from '@b-jones-rfd/func-help'

      Either.of(1).isRight() // true
      Either.left('boom').isRight() // false
    • Apply f to the Right value; a Left passes through unchanged. If f throws, the error propagates from this call; it is not captured as a Left (use tryCatch for that).

      Type Parameters

      • B

        The new Right type.

      Parameters

      • f: (r: R) => B

        The function to apply to the Right value.

      Returns Either<L, B>

      A Right holding f(value), or this Left.

      import { Either } from '@b-jones-rfd/func-help'

      Either.right<number, string>(3).map((n) => n * 2) // Right(6)
      Either.left<string, number>('bad').map((n) => n * 2) // Left('bad')
    • Apply f to the Left value; a Right passes through unchanged. If f throws, the error propagates from this call; it is not captured as a Left.

      This is Haskell's first (Data.Bifunctor), renamed because first doesn't say which side it maps.

      Type Parameters

      • L2

        The new Left type.

      Parameters

      • f: (l: L) => L2

        The function to apply to the Left value.

      Returns Either<L2, R>

      A Left holding f(value), or this Right.

      import { Either } from '@b-jones-rfd/func-help'

      Either.left<string, number>('bad port').mapLeft((m) => new Error(m))
      // Left(Error('bad port'))
      Either.right<number, string>(80).mapLeft((m) => new Error(m)) // Right(80)
    • Pattern matching. If a handler throws, the error propagates from this call.

      Haskell has no counterpart; it uses case or either. Taking a handlers object names each branch at the call site, and the handlers may return different types.

      Type Parameters

      • T extends { left: (l: L) => any; right: (r: R) => any }

        The handlers object, with a left and a right function.

      Parameters

      • handlers: T

        A left handler for a Left and a right handler for a Right.

      Returns ReturnType<T["left"]> | ReturnType<T["right"]>

      What the handler for this branch returns.

      import { Either } from '@b-jones-rfd/func-help'

      Either.right<number, string>(3).match({
      left: (e: string) => `Error: ${e}`,
      right: (n: number) => n * 2,
      }) // 6, typed string | number
    • Swap Left and Right branches.

      Returns Either<R, L>

      A Right holding the Left value, or a Left holding the Right value.

      import { Either } from '@b-jones-rfd/func-help'

      Either.left<string, number>('bad').swap() // Right('bad')
    • Run a side effect with the Right value, keeping this Either as it is; a Left passes through without calling f. If f throws, the error propagates from this call; it is not captured as a Left.

      Haskell has no counterpart; the name matches IO#tap and AsyncIO#tap.

      Parameters

      • f: (r: R) => void

        The side effect, given the Right value; its return is ignored.

      Returns Either<L, R>

      This Either.

      import { Either } from '@b-jones-rfd/func-help'

      const seen: number[] = []
      Either.right<number, string>(7).tap((n) => {
      seen.push(n)
      }) // Right(7), and seen is [7]
    • Run a do block over Either: Haskell's do notation, with x <- m written const x = yield* m.

      Each yield* m binds the Right value of m, typed with no annotation. The first Left stops the block there, and the result is that Left. The block runs at once, so a throw in it propagates from this call. A plain yield (without *) binds unknown; use yield*.

      The result's Left type is the union of the Left types of every Either the block yields.

      Type Parameters

      • Y extends Either<any, any>

        The Eithers the block yields; inferred.

      • A

        The value the block returns.

      Parameters

      • block: () => Generator<Y, A, unknown>

        A generator function that yield*s Eithers and returns the result.

      Returns Either<Y extends Either<L, any> ? L : never, A>

      A Right holding what the block returns, or the first Left.

      import { Either } from '@b-jones-rfd/func-help'

      const parsePort = (s: string): Either<string, number> => {
      const n = Number(s)
      return Number.isInteger(n) ? Either.right(n) : Either.left(`bad port ${s}`)
      }
      const lookupHost = (port: number): Either<Error, string> =>
      port === 80 ? Either.right('example.com') : Either.left(new Error('no host'))

      const address = Either.do(function* () {
      const port = yield* parsePort('80') // number
      const host = yield* lookupHost(port) // string
      return `${host}:${port}`
      }) // Either<string | Error, string>, Right('example.com:80')
    • Convert a nullable/undefinable value into an Either, using the provided onNull thunk to create a Left value when the input is null or undefined. If onNull throws, the error propagates from this call.

      onNull is a thunk so the Left is only built when it is needed.

      Type Parameters

      • L

        The Left type onNull returns.

      • R

        The non-null value type.

      Parameters

      • value: R | null | undefined

        The value that may be null or undefined.

      • onNull: () => L

        Builds the Left when value is null or undefined.

      Returns Either<L, R>

      A Right holding value, or a Left holding onNull().

      import { Either } from '@b-jones-rfd/func-help'

      const ports = new Map<string, number>([['api', 8080]])
      Either.fromNullable(ports.get('api'), () => 'no api port') // Right(8080)
      Either.fromNullable(ports.get('db'), () => 'no db port') // Left(...)
    • Wrap a value as a Left, Haskell's Left.

      R defaults to never, so name it when the Left must sit beside Rights of a known type, such as in a variable or array.

      Type Parameters

      • L

        The Left type.

      • R = never

        The Right type; defaults to never.

      Parameters

      • value: L

        The Left value, usually an error.

      Returns Either<L, R>

      A Left holding value.

      import { Either } from '@b-jones-rfd/func-help'

      const missing = Either.left<string, number>('missing')
      missing.isLeft() // true
    • Lift a value into a Right with no Left type.

      This is Haskell's pure (equivalently Right); the Left type is fixed at never, so use Either.right when the chain needs a Left type.

      Type Parameters

      • R

        The Right type.

      Parameters

      • value: R

        The Right value.

      Returns Either<never, R>

      A Right holding value, typed Either<never, R>.

      import { Either } from '@b-jones-rfd/func-help'

      Either.of(2).map((n) => n * 2) // Right(4)
    • Wrap a value as a Right, Haskell's Right.

      R comes first so it can be inferred from value while L is named explicitly, as in Either.right<number, string>(1).

      Type Parameters

      • R

        The Right type.

      • L = never

        The Left type; defaults to never.

      Parameters

      • value: R

        The Right value.

      Returns Either<L, R>

      A Right holding value.

      import { Either } from '@b-jones-rfd/func-help'

      const port = Either.right<number, string>(8080)
      port.getOrElse(() => 80) // 8080
    • Turn an array of Eithers into an Either of an array: a Right holding every Right value in input order, or the first Left. An empty array gives Right([]). Nothing in it calls caller code, so it never throws.

      This is Haskell's sequence (Data.Traversable). A tuple gives a tuple: [Either<string, number>, Either<HostError, string>] gives Either<string | HostError, [number, string]>, with no as const. An array gives an array, and the Left is the union of the inputs' Lefts.

      Type Parameters

      • const T extends readonly unknown[]

        The array or tuple of Eithers.

      Parameters

      • items: Eithers<T>

        The Eithers, in order.

      Returns Either<
          LeftOf<T[number]>,
          { -readonly [K in string | number | symbol]: RightOf<T[K]> },
      >

      A Right holding the Right values in input order (a tuple for a tuple), or the first Left.

      import { Either } from '@b-jones-rfd/func-help'

      const port: Either<string, number> = Either.right(8080)
      const host: Either<string, string> = Either.right('localhost')

      Either.sequence([host, port]) // Right(['localhost', 8080]), Either<string, [string, number]>
      Either.sequence([host, Either.left('no port')]) // Left('no port')
    • Apply f to each item in order and collect the Rights into one array; the first Left stops it, and f is not called for the items after. An empty array gives Right([]). If f throws, the error propagates from this call; it is not captured as a Left.

      This is Haskell's traverse (also mapM). Like Array#map, f also gets the item's index.

      Type Parameters

      • T

        The item type.

      • L

        The Left type f returns.

      • A

        The Right type f returns.

      Parameters

      • items: readonly T[]

        The items, in order.

      • f: (item: T, index: number) => Either<L, A>

        Turns one item into an Either, given the item and its index.

      Returns Either<L, A[]>

      A Right holding every Right value in input order, or the first Left.

      import { Either } from '@b-jones-rfd/func-help'

      const parsePort = (s: string): Either<string, number> =>
      /^\d+$/.test(s) ? Either.right(Number(s)) : Either.left(`'${s}' is not a port`)

      Either.traverse(['80', '443'], parsePort) // Right([80, 443])
      Either.traverse(['80', 'http', 'x'], parsePort) // Left("'http' is not a port")
    • Run effect, returning its result as a Right, or what it throws as a Left. Without onError the Left is the thrown value, typed unknown.

      Haskell has no counterpart: it is the bridge from code that throws into Either. Only a throw from effect is captured.

      Type Parameters

      • R

        The type effect returns.

      Parameters

      • effect: () => R

        The code that may throw.

      Returns Either<unknown, R>

      A Right holding the result, or a Left holding the thrown value.

      import { Either } from '@b-jones-rfd/func-help'

      const parsed = Either.tryCatch((): unknown => JSON.parse('{'))
      parsed.isLeft() // true; the Left is the SyntaxError, typed unknown
    • Run effect, returning its result as a Right, or what it throws mapped through onError as a Left.

      Haskell has no counterpart: it is the bridge from code that throws into Either, and onError gives the Left a type in place of unknown. Only a throw from effect is captured; if onError throws, the error propagates from this call.

      Type Parameters

      • R

        The type effect returns.

      • E

        The Left type onError returns.

      Parameters

      • effect: () => R

        The code that may throw.

      • onError: (e: unknown) => E

        Maps the thrown value to the Left.

      Returns Either<E, R>

      A Right holding the result, or a Left holding onError(thrown).

      import { Either } from '@b-jones-rfd/func-help'

      const parsed = Either.tryCatch(
      (): unknown => JSON.parse('{'),
      (e) => (e instanceof Error ? e.message : String(e))
      )
      parsed.fold(
      (message) => `Invalid JSON: ${message}`,
      () => 'ok'
      )