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

    Class IO<A>

    A synchronous side effect that has not run yet.

    Building and composing an IO performs nothing, so effects stay referentially transparent until .run() is invoked, once, at the edge of the program.

    A throw in an effect or a caller-supplied function is thrown from run(), not from the call that built the IO.

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

    const lines: string[] = []
    const now: IO<Date> = IO.from(() => new Date())
    const putStrLn = (msg: string): IO<void> =>
    IO.from(() => {
    lines.push(msg)
    })

    const showTime: IO<void> = now
    .map((date) => date.toISOString())
    .bind(putStrLn)

    showTime.run() // lines now holds the ISO timestamp

    Type Parameters

    • A

      The value the effect produces.

    Implements

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

      It exists for yield*, not for spreading: [...io] is a one-element array holding this IO itself, and does not run it.

      Returns Generator<IO<A>, A, unknown>

      A generator that yields this IO once.

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

      IO.do(function* () {
      const n = yield* IO.of(2) // calls this method
      return n * 2
      }).run() // 4
    • Capture a throw as data: an IO that runs this one and produces an Except, ok holding the value or failed holding what was thrown.

      A throw anywhere in the chain built before attempt (the effect, a map or tap function, a bind step) becomes a failed Except, so run() of the result never throws. A non-Error throw is wrapped as Except.tryCatch wraps it, with the original as cause. A function chained after attempt throws from run() as usual. A promise the IO returns is not awaited, so attempt does not capture its rejection; use AsyncIO#attempt for that.

      This is Haskell's try (Control.Exception), renamed because try reads as the statement.

      Returns IO<Except<A>>

      An IO that produces ok holding this IO's value, or failed holding the error it threw.

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

      const readConfig = IO.from((): string => {
      throw new Error('no config file')
      })

      const message: string = readConfig
      .attempt()
      .run()
      .fold(
      (e) => `failed: ${e.message}`,
      (text) => text
      ) // 'failed: no config file'
    • Sequence a further effect that depends on this IO's value.

      If f throws, the error is thrown from run().

      This is Haskell's >>=.

      Type Parameters

      • B

        The value type of the next effect.

      Parameters

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

        The function that builds the next effect from the value.

      Returns IO<B>

      An IO that runs this effect, then the one f returns.

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

      const total: number = IO.of(2)
      .bind((n) => IO.from(() => n + 1))
      .run() // 3
    • Transform the value the effect produces, without running it.

      If f throws, the error is thrown from run().

      This is Haskell's fmap, named map after Array.prototype.map.

      Type Parameters

      • B

        The new value type.

      Parameters

      • f: (a: A) => B

        The function to apply to the produced value.

      Returns IO<B>

      An IO that produces f of this IO's value.

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

      const doubled: number = IO.of(21)
      .map((n) => n * 2)
      .run() // 42
    • Perform the side effect and return its result.

      Haskell has no safe equivalent: its runtime runs main, and the nearest function is unsafePerformIO, so call run() only at the program's edge.

      Returns A

      The value the effect produces.

      TypeError When a bind step returns a monad of another kind instead of an IO. The types rule this out; only an untyped Do.run/Do.with or a cast can reach it.

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

      const value: string = IO.of('hello').run() // 'hello'
    • Perform an additional side effect with the current value, keeping the original result.

      If sideEffect throws, the error is thrown from run().

      Haskell has no direct counterpart; the nearest is io >>= \a -> f a >> pure a.

      Parameters

      • sideEffect: (a: A) => void

        The effect to perform with the value; its return is ignored.

      Returns IO<A>

      An IO that produces this IO's value after sideEffect runs.

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

      const seen: number[] = []
      const n: number = IO.of(7)
      .tap((x) => {
      seen.push(x)
      })
      .run() // 7, and seen is [7]
    • Build an IO from a do block: Haskell's do notation, with x <- m written const x = yield* m.

      Each yield* m binds the value m produces, typed with no annotation. Nothing in the block runs until run() is called, and every run() starts the block afresh. A throw in the block is thrown from run(). A plain yield (without *) binds unknown; use yield*.

      Type Parameters

      • A

        The value the block returns.

      Parameters

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

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

      Returns IO<A>

      An IO that runs the block and produces what it returns.

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

      const sum = IO.do(function* () {
      const a = yield* IO.of(1) // number
      const b = yield* IO.from(() => 2) // number
      return a + b
      }) // IO<number>

      sum.run() // 3
    • Wrap a side effect in IO without running it.

      If effect throws, the error is thrown from run().

      Type Parameters

      • A

        The value the effect produces.

      Parameters

      • effect: () => A

        The side effect to defer.

      Returns IO<A>

      An IO that calls effect each time it is run.

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

      const now: IO<number> = IO.from(() => Date.now())
      const ms: number = now.run()
    • Lift a plain value into IO without any side effect.

      This is Haskell's pure (or return), named of after the JavaScript convention set by Array.of.

      Type Parameters

      • A

        The value's type.

      Parameters

      • value: A

        The value the IO produces when run.

      Returns IO<A>

      An IO that produces value.

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

      const three: number = IO.of(3).run() // 3
    • Turn an array of IOs into one IO that runs them in order and produces their results as an array. An empty array gives [].

      Nothing runs until run(), and every run() runs every item again, in order. The array is copied when the IO is built. A throw from an item is thrown from run(), and the items after it don't run.

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

      Type Parameters

      • const T extends readonly IO<any>[]

        The array or tuple of IOs.

      Parameters

      • items: T

        The IOs, in order.

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

      An IO that produces the results in input order (a tuple for a tuple).

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

      const both = IO.sequence([IO.of('localhost'), IO.from(() => 8080)])
      both.run() // ['localhost', 8080], typed [string, number]
    • An IO that applies f to each item in order, runs the IO it returns, and produces the results as one array. An empty array gives [].

      Nothing runs, and f is not called, until run(); every run() runs every item again, in order. The array is copied when the IO is built, so changing it afterwards doesn't change what run() does. A throw from f or from an item is thrown from run(), and the items after it don't run.

      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 of the IO f returns.

      Parameters

      • items: readonly T[]

        The items, in order.

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

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

      Returns IO<A[]>

      An IO that produces every result in input order.

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

      const read = (key: string): IO<string> => IO.from(() => `value of ${key}`)

      IO.traverse(['host', 'port'], read).run()
      // ['value of host', 'value of port']