Hyperlinkv0.8.0-beta.28

Utils

Utils.SingleShotGenclasseffect/Utils.ts:52
SingleShotGen<T, A>

Yields its wrapped value exactly once through an IterableIterator.

When to use

Use to implement [Symbol.iterator]() on Effect-like types so they can be yield*-ed inside generator functions, such as Effect.gen and Option.gen.

Details

The first call to next() returns { value: self, done: false }. Every subsequent call returns { value: a, done: true } where a is the argument passed to next(). [Symbol.iterator]() returns a new SingleShotGen wrapping the same value, so the outer type can be iterated multiple times.

Example (Yielding a wrapped value in a generator)

import { Utils } from "effect"

const gen = new Utils.SingleShotGen<string, number>("hello")

// First call yields the wrapped value
console.log(gen.next(0))
// { value: "hello", done: false }

// Second call signals completion with the provided value
console.log(gen.next(42))
// { value: 42, done: true }
constructorsGen
Source effect/Utils.ts:5245 lines
export class SingleShotGen<T, A> implements IterableIterator<T, A> {
  private called = false
  readonly self: T

  constructor(self: T) {
    this.self = self
  }

  /**
   * Yields the stored value once, then completes with the value sent back in.
   *
   * **When to use**
   *
   * Use to advance a `SingleShotGen` through its single yield and completion
   * step.
   *
   * @since 2.0.0
   */
  next(a: A): IteratorResult<T, A> {
    return this.called ?
      ({
        value: a,
        done: true
      }) :
      (this.called = true,
        ({
          value: this.self,
          done: false
        }))
  }

  /**
   * Creates a fresh single-shot iterator over the stored value.
   *
   * **When to use**
   *
   * Use to iterate the wrapped value again without reusing the consumed
   * iterator state.
   *
   * @since 2.0.0
   */
  [Symbol.iterator](): IterableIterator<T, A> {
    return new SingleShotGen<T, A>(this.self)
  }
}