All files / iterable/src tee.ts

100% Statements 14/14
100% Branches 4/4
100% Functions 5/5
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46  1x                                   1x 1x 1x   3x     1x 3x   12x 4x 4x 12x         12x 3x     9x        
import { Tuple } from "@benneq/object";
import { generate } from "@benneq/array";
 
/**
 * Creates a {@link Function} that returns a {@link Tuple} of {@link Iterable}s
 * with the given `length`, where each {@link Iterable} yields the same values
 * as the source {@link Iterable}, in the same order.
 *
 * @example
 * ```ts
 * const iterable = [1, 2, 3];
 * const [iterable1, iterable2] = tee(2)(iterable);
 * console.log(iterable1); // 1, 2, 3
 * console.log(iterable2); // 1, 2, 3
 * ```
 *
 * @param length - the length of the {@link Tuple}
 * @returns the tuple of {@link Iterable}s
 */
export const tee =
  <N extends number>(length: N) =>
  <T>(
    iterable: Iterable<T>,
    buffers = generate<IteratorResult<T>[]>(length, () => []),
    iterator = iterable[Symbol.iterator]()
  ): Tuple<IterableIterator<T>, N> => {
    return buffers.map(function* (buffer) {
      while (true) {
        // if the buffer is empty, fetch a new value from the source iterable
        if (!buffer.length) {
          const result = iterator.next();
          for (const buffer of buffers) {
            buffer.push(result);
          }
        }
 
        // source iterable is done, no more values to come
        if ((buffer[0] as IteratorResult<T>).done) {
          return;
        }
 
        yield (buffer.shift() as IteratorResult<T>).value;
      }
    }) as Tuple<IterableIterator<T>, N>;
  };