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

    Class Except<A>

    A value that is either failed, holding an Error, or ok, holding an A.

    map and bind run only on an ok value, so the first failure short-circuits the rest of the chain.

    Haskell's Except e a takes any error type; this Except<A> fixes the error to Error, so every failure carries a message and a stack.

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

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

    const parseNumber = (s: string): Except<number> => {
    const n = parseFloat(s)
    return isNaN(n)
    ? Except.failed(new Error(`'${s}' is not a number`))
    : Except.ok(n)
    }

    const reciprocal = (n: number): Except<number> =>
    n === 0 ? Except.failed(new Error('division by zero')) : Except.ok(1 / n)

    const result = parseNumber('10')
    .bind(reciprocal)
    .fold(
    (err) => `Error: ${err.message}`,
    (value) => `Reciprocal is ${value}`
    )
    // result === 'Reciprocal is 0.1'

    Type Parameters

    • A

      The ok value type.

    Implements

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

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

      Returns Generator<Except<A>, A, unknown>

      A generator that yields this Except once.

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

      Except.do(function* () {
      const n = yield* Except.ok(2) // calls this method
      return n * 2
      }) // ok 4
    • Chain a step that may itself fail; the first failure short-circuits.

      If f throws, the error propagates from this call; it is not captured as a failure (use tryCatch for that).

      This is Haskell's >>=.

      Type Parameters

      • B

        The new ok value type.

      Parameters

      • f: (a: A) => Except<B>

        The next step, given the ok value.

      Returns Except<B>

      The Except that f returns, or this failure.

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

      const half = (n: number): Except<number> =>
      n % 2 === 0 ? Except.ok(n / 2) : Except.failed(new Error('odd'))
      Except.ok(4).bind(half) // ok 2
      Except.ok(3).bind(half) // failed: odd
    • Recover from a failure: handler gets the error and its Except replaces this one. An ok value passes through without calling handler.

      If handler throws, the error propagates from this call; it is not captured as a failure.

      This is Haskell's catchError (MonadError). The handler must keep the value type: it returns Except<A>.

      Parameters

      • handler: (e: Error) => Except<A>

        Given the error, returns the Except to use instead.

      Returns Except<A>

      The Except handler returns, or this ok value.

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

      Except.failed<number>(new Error('no port')).catchError(() =>
      Except.ok(8080)
      ) // ok 8080
    • Collapse the Except into one value by handling both cases.

      Plays the part of Haskell's either, with the failure handler first. If onError or onSuccess throws, the error propagates from this call.

      Type Parameters

      • B

        The type both handlers return.

      Parameters

      • onError: (e: Error) => B

        Called with the error when failed.

      • onSuccess: (a: A) => B

        Called with the value when ok.

      Returns B

      What the handler for this case returns.

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

      const label = Except.ok(3).fold(
      (e) => `failed: ${e.message}`,
      (n) => `got ${n}`
      )
      // label === 'got 3'
    • Extract the ok value, or compute a default from the error when failed.

      The fallback receives the error so the default can depend on why the computation failed. If fallback throws, the error propagates from this call.

      Parameters

      • fallback: (e: Error) => A

        Builds the value to return from the error.

      Returns A

      The ok value, or what fallback returns.

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

      const n = Except.failed<number>(new Error('bad')).getOrElse(() => 0)
      // n === 0
    • Report whether this Except failed.

      It does not narrow the type; use fold or match to reach the error.

      Returns boolean

      true if this Except is failed.

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

      Except.failed(new Error('bad')).isError() // true
    • Report whether this Except is ok.

      It does not narrow the type; use fold or match to reach the value.

      Returns boolean

      true if this Except is ok.

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

      Except.ok(3).isOk() // true
    • Apply f to the ok value; a failure passes through unchanged.

      If f throws, the error propagates from this call; it is not captured as a failure (use tryCatch for that).

      Type Parameters

      • B

        The new ok value type.

      Parameters

      • f: (a: A) => B

        The function to apply to the ok value.

      Returns Except<B>

      Ok holding f(value), or this failure.

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

      Except.ok(3).map((n) => n * 2) // ok 6
    • Apply f to the error; an ok value passes through unchanged.

      If f throws, the error propagates from this call; it is not captured as a failure.

      This is Haskell's withExcept, renamed to match Either#mapLeft. f must return an Error, because an Except always fails with one; to leave Error behind, use toEither().mapLeft(…).

      Parameters

      • f: (e: Error) => Error

        The function to apply to the error.

      Returns Except<A>

      Failed holding f(error), or this ok value.

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

      Except.failed<number>(new Error('timeout')).mapError(
      (e) => new Error(`loading config: ${e.message}`, { cause: e })
      ) // failed: loading config: timeout
    • Pattern-match on the result, calling failed with the error or ok with the value.

      Haskell has no counterpart; it is fold with named handlers in a { failed, ok } object, so the call site cannot swap them by position. If a handler throws, the error propagates from this call.

      Type Parameters

      • B

        The type both handlers return.

      Parameters

      • handlers: { failed: (e: Error) => B; ok: (a: A) => B }

        failed runs with the error, ok with the value.

      Returns B

      What the handler for this case returns.

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

      const label = Except.failed<number>(new Error('bad')).match({
      failed: (e) => `failed: ${e.message}`,
      ok: (n) => `got ${n}`,
      })
      // label === 'failed: bad'
    • Run a side effect with the ok value, keeping this Except as it is; a failure passes through without calling f.

      If f throws, the error propagates from this call; it is not captured as a failure.

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

      Parameters

      • f: (a: A) => void

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

      Returns Except<A>

      This Except.

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

      const seen: number[] = []
      Except.ok(7).tap((n) => {
      seen.push(n)
      }) // ok 7, and seen is [7]
    • Turn this Except into an Either: ok becomes a Right, a failure becomes a Left holding the same Error.

      This is Haskell's runExcept. From there mapLeft can change the error type, which mapError can't. Nothing in it calls caller code, so it never throws.

      Returns Either<Error, A>

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

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

      Except.failed<number>(new Error('bad'))
      .toEither()
      .mapLeft((e) => e.message) // Left('bad')
    • Run a do block over Except: Haskell's do notation, with x <- m written const x = yield* m.

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

      Type Parameters

      • A

        The value the block returns.

      Parameters

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

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

      Returns Except<A>

      An ok Except holding what the block returns, or the first failure.

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

      const parse = (s: string): Except<number> =>
      Number.isNaN(Number(s))
      ? Except.failed(new Error(`'${s}' is not a number`))
      : Except.ok(Number(s))

      const sum = Except.do(function* () {
      const a = yield* parse('1') // number
      const b = yield* parse('2') // number
      return a + b
      }) // Except<number>, ok 3
    • Create a failed Except holding error.

      Stands in for Haskell's throwError; the name pairs with ok. A defaults to never so the result is assignable to any Except<A>.

      Type Parameters

      • A = never

        The ok value type the result is used as.

      Parameters

      • error: Error

        The error the computation failed with.

      Returns Except<A>

      A failed Except holding error.

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

      const r: Except<number> = Except.failed(new Error('missing'))
    • Turn an Either whose Left is an Error into an Except: a Right becomes ok, a Left becomes a failure holding the same Error.

      This is Haskell's except, named after the package's from* constructors. Any Left type that is an Error (or a subclass) is accepted; for another Left, mapLeft it to an Error first. Nothing in it calls caller code, so it never throws.

      Type Parameters

      • A

        The Right (ok) value type.

      Parameters

      • either: Either<Error, A>

        The Either to convert.

      Returns Except<A>

      Ok holding the Right value, or failed holding the Left Error.

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

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

      Except.fromEither(parsePort('80').mapLeft((m) => new Error(m))) // ok 80
      Except.fromEither(parsePort('x').mapLeft((m) => new Error(m)))
      // failed: bad port 'x'
    • Turn a possibly absent value into an Except, failing with the error from onNull when the value is null or undefined.

      onNull is a thunk so the error, and its stack trace, is built only when the value is absent. If onNull throws, the error propagates from this call.

      Type Parameters

      • A

        The value type when present.

      Parameters

      • value: A | null | undefined

        The value that may be null or undefined.

      • onNull: () => Error

        Builds the error for an absent value.

      Returns Except<A>

      Ok holding value, or failed holding the error from onNull.

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

      const ports = new Map<string, number>([['http', 80]])
      const port = Except.fromNullable(
      ports.get('https'),
      () => new Error('no https port')
      )
      // port.isError() === true
    • Lift a value into an ok Except; the Monad interface's name for ok.

      Type Parameters

      • A

        The ok value type.

      Parameters

      • value: A

        The successful value.

      Returns Except<A>

      An ok Except holding value.

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

      const r: Except<number> = Except.of(3)
    • Create an ok Except holding value.

      Stands in for Haskell's return; the name pairs with failed.

      Type Parameters

      • A

        The ok value type.

      Parameters

      • value: A

        The successful value.

      Returns Except<A>

      An ok Except holding value.

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

      const r: Except<number> = Except.ok(3)
    • Turn an array of Excepts into an Except of an array: ok holding every value in input order, or the first failure. An empty array gives ok []. Nothing in it calls caller code, so it never throws.

      This is Haskell's sequence (Data.Traversable). A tuple gives a tuple: [Except<number>, Except<string>] gives Except<[number, string]>, with no as const. An array gives an array.

      Type Parameters

      • const T extends readonly unknown[]

        The array or tuple of Excepts.

      Parameters

      • items: Excepts<T>

        The Excepts, in order.

      Returns Except<{ -readonly [K in string | number | symbol]: ValueOf<T[K]> }>

      Ok holding the values in input order (a tuple for a tuple), or the first failure.

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

      Except.sequence([Except.ok('localhost'), Except.ok(8080)])
      // ok ['localhost', 8080], Except<[string, number]>
      Except.sequence([Except.ok('localhost'), Except.failed(new Error('no port'))])
      // failed: no port
    • Apply f to each item in order and collect the values into one array; the first failure stops it, and f is not called for the items after. An empty array gives ok [].

      If f throws, the error propagates from this call; it is not captured as a failure.

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

      Type Parameters

      • T

        The item type.

      • A

        The value type f returns.

      Parameters

      • items: readonly T[]

        The items, in order.

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

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

      Returns Except<A[]>

      Ok holding every value in input order, or the first failure.

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

      const parsePort = (s: string): Except<number> =>
      /^\d+$/.test(s)
      ? Except.ok(Number(s))
      : Except.failed(new Error(`'${s}' is not a port`))

      Except.traverse(['80', '443'], parsePort) // ok [80, 443]
      Except.traverse(['80', 'http'], parsePort) // failed: 'http' is not a port
    • Run effect and capture a throw from it as a failed Except.

      This is the bridge from throwing code; no other member captures throws. Without onError, a thrown value that is not an Error is wrapped in one, with the original kept as its cause; if the value can't be turned into a string, the message is 'Non-Error value thrown'. Only a throw from effect is captured; if onError throws, the error propagates from this call.

      Type Parameters

      • A

        The value type effect returns.

      Parameters

      • effect: () => A

        The code that may throw.

      • OptionalonError: (e: unknown) => Error

        Optional; turns the thrown value into the failure's Error.

      Returns Except<A>

      Ok holding the result of effect, or failed holding the error.

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

      const text = '{"port": 80}'
      const config = Except.tryCatch(
      () => JSON.parse(text) as unknown,
      (e) => new Error('invalid config', { cause: e })
      )