@mirei/ts-collections
    Preparing search index...

    Interface IImmutableCollection<TElement>

    interface IImmutableCollection<TElement> {
        get comparator(): | EqualityComparator<TElement, TElement>
        | OrderComparator<TElement, TElement>;
        get length(): number;
        "[iterator]"(): Iterator<TElement, any, any>;
        add(element: TElement): IImmutableCollection<TElement>;
        addAll<TSource>(
            collection: Iterable<TSource>,
        ): IImmutableCollection<TElement>;
        aggregate<TAccumulate = TElement, TResult = TAccumulate>(
            accumulator: Accumulator<TElement, TAccumulate>,
            seed?: TAccumulate,
            resultSelector?: Selector<TAccumulate, TResult>,
        ): TAccumulate | TResult;
        aggregateBy<TKey, TAccumulate = TElement>(
            keySelector: Selector<TElement, TKey>,
            seedSelector: TAccumulate | Selector<TKey, TAccumulate>,
            accumulator: Accumulator<TElement, TAccumulate>,
            keyComparator?: EqualityComparator<TKey, TKey>,
        ): IEnumerable<KeyValuePair<TKey, TAccumulate>>;
        all(predicate: Predicate<TElement>): boolean;
        any(predicate?: Predicate<TElement>): boolean;
        append(element: TElement): IEnumerable<TElement>;
        atLeast(count: number, predicate?: Predicate<TElement>): boolean;
        atMost(count: number, predicate?: Predicate<TElement>): boolean;
        average(selector?: Selector<TElement, number>): number;
        cartesian<TSecond>(
            iterable: Iterable<TSecond>,
        ): IEnumerable<[TElement, TSecond]>;
        cast<TResult>(): IEnumerable<TResult>;
        chunk(size: number): IEnumerable<IEnumerable<TElement>>;
        clear(): IImmutableCollection<TElement>;
        combinations(size?: number): IEnumerable<IEnumerable<TElement>>;
        compact(): IEnumerable<NonNullable<TElement>>;
        concat(iterable: Iterable<TElement>): IEnumerable<TElement>;
        contains(
            element: TElement,
            comparator?: EqualityComparator<TElement, TElement>,
        ): boolean;
        containsAll<TSource>(collection: Iterable<TSource>): boolean;
        correlation<TSecond>(
            iterable: Iterable<TSecond>,
            selector?: Selector<TElement, number>,
            otherSelector?: Selector<TSecond, number>,
        ): number;
        correlationBy(
            leftSelector: Selector<TElement, number>,
            rightSelector: Selector<TElement, number>,
        ): number;
        count(predicate?: Predicate<TElement>): number;
        countBy<TKey>(
            keySelector: Selector<TElement, TKey>,
            comparator?: EqualityComparator<TKey, TKey>,
        ): IEnumerable<KeyValuePair<TKey, number>>;
        covariance<TSecond>(
            iterable: Iterable<TSecond>,
            selector?: Selector<TElement, number>,
            otherSelector?: Selector<TSecond, number>,
            sample?: boolean,
        ): number;
        covarianceBy(
            leftSelector: Selector<TElement, number>,
            rightSelector: Selector<TElement, number>,
            sample?: boolean,
        ): number;
        cycle(count?: number): IEnumerable<TElement>;
        defaultIfEmpty(value?: TElement | null): IEnumerable<TElement | null>;
        disjoint<TSecond>(
            iterable: Iterable<TSecond>,
            comparator?: EqualityComparator<TElement | TSecond, TElement | TSecond>,
        ): boolean;
        disjointBy<TSecond, TKey, TSecondKey>(
            iterable: Iterable<TSecond>,
            keySelector: Selector<TElement, TKey>,
            otherKeySelector: Selector<TSecond, TSecondKey>,
            keyComparator?: EqualityComparator<TKey | TSecondKey, TKey | TSecondKey>,
        ): boolean;
        distinct(
            keyComparator?: EqualityComparator<TElement, TElement>,
        ): IEnumerable<TElement>;
        distinctBy<TKey>(
            keySelector: Selector<TElement, TKey>,
            keyComparator?: EqualityComparator<TKey, TKey>,
        ): IEnumerable<TElement>;
        distinctUntilChanged(
            comparator?: EqualityComparator<TElement, TElement>,
        ): IEnumerable<TElement>;
        distinctUntilChangedBy<TKey>(
            keySelector: Selector<TElement, TKey>,
            keyComparator?: EqualityComparator<TKey, TKey>,
        ): IEnumerable<TElement>;
        elementAt(index: number): TElement;
        elementAtOrDefault(index: number): TElement | null;
        exactly(count: number, predicate?: Predicate<TElement>): boolean;
        except(
            iterable: Iterable<TElement>,
            comparator?:
                | EqualityComparator<TElement, TElement>
                | OrderComparator<TElement, TElement>,
        ): IEnumerable<TElement>;
        exceptBy<TKey>(
            iterable: Iterable<TElement>,
            keySelector: Selector<TElement, TKey>,
            keyComparator?:
                | EqualityComparator<TKey, TKey>
                | OrderComparator<TKey, TKey>,
        ): IEnumerable<TElement>;
        first<TFiltered>(predicate: TypePredicate<TElement, TFiltered>): TFiltered;
        first(predicate?: Predicate<TElement>): TElement;
        firstOrDefault<TFiltered>(
            predicate: TypePredicate<TElement, TFiltered>,
        ): TFiltered | null;
        firstOrDefault(predicate?: Predicate<TElement>): TElement | null;
        forEach(action: IndexedAction<TElement>): void;
        groupBy<TKey>(
            keySelector: Selector<TElement, TKey>,
            keyComparator?: EqualityComparator<TKey, TKey>,
        ): IEnumerable<IGroup<TKey, TElement>>;
        groupJoin<TInner, TKey, TResult>(
            innerEnumerable: IEnumerable<TInner>,
            outerKeySelector: Selector<TElement, TKey>,
            innerKeySelector: Selector<TInner, TKey>,
            resultSelector: JoinSelector<TElement, IEnumerable<TInner>, TResult>,
            keyComparator?: EqualityComparator<TKey, TKey>,
        ): IEnumerable<TResult>;
        index(): IEnumerable<[number, TElement]>;
        interleave<TSecond>(
            iterable: Iterable<TSecond>,
        ): IEnumerable<TElement | TSecond>;
        intersect(
            iterable: Iterable<TElement>,
            comparator?:
                | EqualityComparator<TElement, TElement>
                | OrderComparator<TElement, TElement>,
        ): IEnumerable<TElement>;
        intersectBy<TKey>(
            iterable: Iterable<TElement>,
            keySelector: Selector<TElement, TKey>,
            keyComparator?:
                | EqualityComparator<TKey, TKey>
                | OrderComparator<TKey, TKey>,
        ): IEnumerable<TElement>;
        intersperse<TSeparator = TElement>(
            separator: TSeparator,
        ): IEnumerable<TElement | TSeparator>;
        isEmpty(): boolean;
        join<TInner, TKey, TResult>(
            innerEnumerable: IEnumerable<TInner>,
            outerKeySelector: Selector<TElement, TKey>,
            innerKeySelector: Selector<TInner, TKey>,
            resultSelector: JoinSelector<TElement, TInner, TResult>,
            keyComparator?: EqualityComparator<TKey, TKey>,
        ): IEnumerable<TResult>;
        last<TFiltered>(predicate: TypePredicate<TElement, TFiltered>): TFiltered;
        last(predicate?: Predicate<TElement>): TElement;
        lastOrDefault<TFiltered>(
            predicate: TypePredicate<TElement, TFiltered>,
        ): TFiltered | null;
        lastOrDefault(predicate?: Predicate<TElement>): TElement | null;
        leftJoin<TInner, TKey, TResult>(
            innerEnumerable: IEnumerable<TInner>,
            outerKeySelector: Selector<TElement, TKey>,
            innerKeySelector: Selector<TInner, TKey>,
            resultSelector: JoinSelector<TElement, TInner, TResult>,
            keyComparator?: EqualityComparator<TKey, TKey>,
        ): IEnumerable<TResult>;
        max(selector?: Selector<TElement, number>): number;
        maxBy<TKey>(
            keySelector: Selector<TElement, TKey>,
            comparator?: OrderComparator<TKey, TKey>,
        ): TElement;
        median(
            selector?: Selector<TElement, number>,
            tie?: MedianTieStrategy,
        ): number;
        min(selector?: Selector<TElement, number>): number;
        minBy<TKey>(
            keySelector: Selector<TElement, TKey>,
            comparator?: OrderComparator<TKey, TKey>,
        ): TElement;
        mode<TKey>(keySelector?: Selector<TElement, TKey>): TElement;
        modeOrDefault<TKey>(
            keySelector?: Selector<TElement, TKey>,
        ): TElement | null;
        multimode<TKey>(
            keySelector?: Selector<TElement, TKey>,
        ): IEnumerable<TElement>;
        none(predicate?: Predicate<TElement>): boolean;
        ofType<TResult extends ObjectType>(
            type: TResult,
        ): IEnumerable<InferredType<TResult>>;
        order(
            comparator?: OrderComparator<TElement, TElement>,
        ): IOrderedEnumerable<TElement>;
        orderBy<TKey>(
            keySelector: Selector<TElement, TKey>,
            comparator?: OrderComparator<TKey, TKey>,
        ): IOrderedEnumerable<TElement>;
        orderByDescending<TKey>(
            keySelector: Selector<TElement, TKey>,
            comparator?: OrderComparator<TKey, TKey>,
        ): IOrderedEnumerable<TElement>;
        orderDescending(
            comparator?: OrderComparator<TElement, TElement>,
        ): IOrderedEnumerable<TElement>;
        pairwise(
            resultSelector?: PairwiseSelector<
                TElement,
                TElement,
                [TElement, TElement],
            >,
        ): IEnumerable<[TElement, TElement]>;
        partition<TFiltered>(
            predicate: TypePredicate<TElement, TFiltered>,
        ): [IEnumerable<TFiltered>, IEnumerable<Exclude<TElement, TFiltered>>];
        partition(
            predicate: Predicate<TElement>,
        ): [IEnumerable<TElement>, IEnumerable<TElement>];
        percentile(
            percent: number,
            selector?: Selector<TElement, number>,
            strategy?: PercentileStrategy,
        ): number;
        permutations(size?: number): IEnumerable<IEnumerable<TElement>>;
        pipe<TResult>(operator: PipeOperator<TElement, TResult>): TResult;
        prepend(element: TElement): IEnumerable<TElement>;
        product(selector?: Selector<TElement, number>): number;
        reverse(): IEnumerable<TElement>;
        rightJoin<TInner, TKey, TResult>(
            innerEnumerable: IEnumerable<TInner>,
            outerKeySelector: Selector<TElement, TKey>,
            innerKeySelector: Selector<TInner, TKey>,
            resultSelector: JoinSelector<TElement | null, TInner, TResult>,
            keyComparator?: EqualityComparator<TKey, TKey>,
        ): IEnumerable<TResult>;
        rotate(shift: number): IEnumerable<TElement>;
        scan<TAccumulate = TElement>(
            accumulator: Accumulator<TElement, TAccumulate>,
            seed?: TAccumulate,
        ): IEnumerable<TAccumulate>;
        select<TResult>(
            selector: IndexedSelector<TElement, TResult>,
        ): IEnumerable<TResult>;
        selectMany<TResult>(
            selector: IndexedSelector<TElement, Iterable<TResult, any, any>>,
        ): IEnumerable<TResult>;
        sequenceEqual(
            iterable: Iterable<TElement>,
            comparator?: EqualityComparator<TElement, TElement>,
        ): boolean;
        shuffle(): IEnumerable<TElement>;
        single<TFiltered>(predicate: TypePredicate<TElement, TFiltered>): TFiltered;
        single(predicate?: Predicate<TElement>): TElement;
        singleOrDefault<TFiltered>(
            predicate: TypePredicate<TElement, TFiltered>,
        ): TFiltered | null;
        singleOrDefault(predicate?: Predicate<TElement>): TElement | null;
        size(): number;
        skip(count: number): IEnumerable<TElement>;
        skipLast(count: number): IEnumerable<TElement>;
        skipUntil<TFiltered>(
            predicate: IndexedTypePredicate<TElement, TFiltered>,
        ): IEnumerable<TFiltered>;
        skipUntil(predicate: IndexedPredicate<TElement>): IEnumerable<TElement>;
        skipWhile(predicate: IndexedPredicate<TElement>): IEnumerable<TElement>;
        span<TFiltered>(
            predicate: TypePredicate<TElement, TFiltered>,
        ): [IEnumerable<TFiltered>, IEnumerable<TElement>];
        span(
            predicate: Predicate<TElement>,
        ): [IEnumerable<TElement>, IEnumerable<TElement>];
        standardDeviation(
            selector?: Selector<TElement, number>,
            sample?: boolean,
        ): number;
        step(step: number): IEnumerable<TElement>;
        sum(selector?: Selector<TElement, number>): number;
        take(count: number): IEnumerable<TElement>;
        takeLast(count: number): IEnumerable<TElement>;
        takeUntil<TFiltered>(
            predicate: IndexedTypePredicate<TElement, TFiltered>,
        ): IEnumerable<TFiltered>;
        takeUntil(predicate: IndexedPredicate<TElement>): IEnumerable<TElement>;
        takeWhile<TFiltered>(
            predicate: IndexedTypePredicate<TElement, TFiltered>,
        ): IEnumerable<TFiltered>;
        takeWhile(predicate: IndexedPredicate<TElement>): IEnumerable<TElement>;
        tap(action: IndexedAction<TElement>): IEnumerable<TElement>;
        toArray(): TElement[];
        toCircularLinkedList(
            comparator?: EqualityComparator<TElement, TElement>,
        ): CircularLinkedList<TElement>;
        toCircularQueue(
            comparator?: EqualityComparator<TElement, TElement>,
        ): CircularQueue<TElement>;
        toCircularQueue(
            capacity: number,
            comparator?: EqualityComparator<TElement, TElement>,
        ): CircularQueue<TElement>;
        toDictionary<TKey, TValue>(
            keySelector: Selector<TElement, TKey>,
            valueSelector: Selector<TElement, TValue>,
            valueComparator?: EqualityComparator<TValue, TValue>,
        ): Dictionary<TKey, TValue>;
        toEnumerableSet(): EnumerableSet<TElement>;
        toImmutableCircularQueue(
            comparator?: EqualityComparator<TElement, TElement>,
        ): ImmutableCircularQueue<TElement>;
        toImmutableCircularQueue(
            capacity: number,
            comparator?: EqualityComparator<TElement, TElement>,
        ): ImmutableCircularQueue<TElement>;
        toImmutableDictionary<TKey, TValue>(
            keySelector: Selector<TElement, TKey>,
            valueSelector: Selector<TElement, TValue>,
            valueComparator?: EqualityComparator<TValue, TValue>,
        ): ImmutableDictionary<TKey, TValue>;
        toImmutableList(
            comparator?: EqualityComparator<TElement, TElement>,
        ): ImmutableList<TElement>;
        toImmutablePriorityQueue(
            comparator?: OrderComparator<TElement, TElement>,
        ): ImmutablePriorityQueue<TElement>;
        toImmutableQueue(
            comparator?: EqualityComparator<TElement, TElement>,
        ): ImmutableQueue<TElement>;
        toImmutableSet(): ImmutableSet<TElement>;
        toImmutableSortedDictionary<TKey, TValue>(
            keySelector: Selector<TElement, TKey>,
            valueSelector: Selector<TElement, TValue>,
            keyComparator?: OrderComparator<TKey, TKey>,
            valueComparator?: EqualityComparator<TValue, TValue>,
        ): ImmutableSortedDictionary<TKey, TValue>;
        toImmutableSortedSet(
            comparator?: OrderComparator<TElement, TElement>,
        ): ImmutableSortedSet<TElement>;
        toImmutableStack(
            comparator?: EqualityComparator<TElement, TElement>,
        ): ImmutableStack<TElement>;
        toLinkedList(
            comparator?: EqualityComparator<TElement, TElement>,
        ): LinkedList<TElement>;
        toList(comparator?: EqualityComparator<TElement, TElement>): List<TElement>;
        toLookup<TKey, TValue>(
            keySelector: Selector<TElement, TKey>,
            valueSelector: Selector<TElement, TValue>,
            keyComparator?: OrderComparator<TKey, TKey>,
        ): ILookup<TKey, TValue>;
        toMap<TKey, TValue>(
            keySelector: Selector<TElement, TKey>,
            valueSelector: Selector<TElement, TValue>,
        ): Map<TKey, TValue>;
        toObject<TKey extends PropertyKey, TValue>(
            keySelector: Selector<TElement, TKey>,
            valueSelector: Selector<TElement, TValue>,
        ): Record<TKey, TValue>;
        toPriorityQueue(
            comparator?: OrderComparator<TElement, TElement>,
        ): PriorityQueue<TElement>;
        toQueue(
            comparator?: EqualityComparator<TElement, TElement>,
        ): Queue<TElement>;
        toSet(): Set<TElement>;
        toSortedDictionary<TKey, TValue>(
            keySelector: Selector<TElement, TKey>,
            valueSelector: Selector<TElement, TValue>,
            keyComparator?: OrderComparator<TKey, TKey>,
            valueComparator?: EqualityComparator<TValue, TValue>,
        ): SortedDictionary<TKey, TValue>;
        toSortedSet(
            comparator?: OrderComparator<TElement, TElement>,
        ): SortedSet<TElement>;
        toStack(
            comparator?: EqualityComparator<TElement, TElement>,
        ): Stack<TElement>;
        toString(): string;
        toString(separator?: string): string;
        toString(separator?: string, selector?: Selector<TElement, string>): string;
        union(
            iterable: Iterable<TElement>,
            comparator?: EqualityComparator<TElement, TElement>,
        ): IEnumerable<TElement>;
        unionBy<TKey>(
            iterable: Iterable<TElement>,
            keySelector: Selector<TElement, TKey>,
            comparator?: EqualityComparator<TKey, TKey>,
        ): IEnumerable<TElement>;
        variance(selector?: Selector<TElement, number>, sample?: boolean): number;
        where<TFiltered>(
            predicate: IndexedTypePredicate<TElement, TFiltered>,
        ): IEnumerable<TFiltered>;
        where(predicate: IndexedPredicate<TElement>): IEnumerable<TElement>;
        windows(size: number): IEnumerable<IEnumerable<TElement>>;
        zip<TSecond>(iterable: Iterable<TSecond>): IEnumerable<[TElement, TSecond]>;
        zip<TSecond, TResult>(
            iterable: Iterable<TSecond>,
            zipper: Zipper<TElement, TSecond, TResult>,
        ): IEnumerable<TResult>;
        zipMany<TIterable extends readonly Iterable<unknown, any, any>[]>(
            ...iterables: [...TIterable[]],
        ): IEnumerable<[TElement, ...UnpackIterableTuple<TIterable>[]]>;
        zipMany<TIterable extends readonly Iterable<unknown, any, any>[], TResult>(
            ...iterablesAndZipper: [
                ...TIterable[],
                ZipManyZipper<[TElement, ...UnpackIterableTuple<TIterable>[]], TResult>,
            ],
        ): IEnumerable<TResult>;
    }

    Type Parameters

    • TElement

    Hierarchy (View Summary)

    Implemented by

    Index

    Accessors

    • get length(): number

      Returns the number of element in this collection.

      Returns number

      The number of elements in this collection.

    Methods

    • Combines the elements of the sequence by applying an accumulator to each element and optionally projecting the final result.

      Type Parameters

      • TAccumulate = TElement

        Type of the intermediate accumulator. Defaults to TElement when no seed is provided.

      • TResult = TAccumulate

        Type returned when a resultSelector is supplied.

      Parameters

      • accumulator: Accumulator<TElement, TAccumulate>

        Function that merges the running accumulator with the next element.

      • Optionalseed: TAccumulate

        Optional initial accumulator value. When omitted, the first element is used as the starting accumulator.

      • OptionalresultSelector: Selector<TAccumulate, TResult>

        Optional projection applied to the final accumulator before it is returned.

      Returns TAccumulate | TResult

      The final accumulator (or its projection).

      Thrown when the sequence is empty and no seed is provided.

      The source sequence is enumerated exactly once. Supply a seed to avoid exceptions on empty sequences and to control the accumulator type.

      const numbers = from([1, 2, 3, 4, 5]);
      const sum = numbers.aggregate((acc, x) => acc + x);
      console.log(sum); // 15

      const product = numbers.aggregate((acc, x) => acc * x, 1);
      console.log(product); // 120
    • Determines whether every element in the sequence satisfies the supplied predicate.

      Parameters

      • predicate: Predicate<TElement>

        Function that evaluates each element and returns true when it satisfies the condition.

      Returns boolean

      true when all elements satisfy the predicate; otherwise, false.

      Enumeration stops as soon as the predicate returns false.

      const numbers = from([1, 2, 3, 4, 5]);
      const allPositive = numbers.all(x => x > 0);
      console.log(allPositive); // true

      const mixedNumbers = from([-1, 2, 3, -4, 5]);
      const allPositive2 = mixedNumbers.all(x => x > 0);
      console.log(allPositive2); // false
    • Determines whether the sequence contains at least one element that matches the optional predicate.

      Parameters

      • Optionalpredicate: Predicate<TElement>

        Optional function used to test elements. When omitted, the method returns true if the sequence contains any element.

      Returns boolean

      true when a matching element is found; otherwise, false.

      When the predicate is omitted, only the first element is inspected, making this more efficient than count() > 0.

      const numbers = from([1, 2, 3, 4, 5]);
      const hasEvenNumber = numbers.any(x => x % 2 === 0);
      console.log(hasEvenNumber); // true

      const oddNumbers = from([1, 3, 5]);
      const hasEvenNumber2 = oddNumbers.any(x => x % 2 === 0);
      console.log(hasEvenNumber2); // false
    • Creates a sequence that yields the current elements followed by the supplied element.

      Parameters

      • element: TElement

        Element appended to the end of the sequence.

      Returns IEnumerable<TElement>

      A new enumerable whose final item is the provided element.

      The source sequence is not modified; enumeration is deferred until the returned sequence is iterated.

      const numbers = from([1, 2, 3]);
      const appended = numbers.append(4).toArray();
      console.log(appended); // [1, 2, 3, 4]
    • Determines whether the sequence contains at least count elements that satisfy the optional predicate.

      Parameters

      • count: number

        Minimum number of matching elements required. Must be greater than or equal to 0.

      • Optionalpredicate: Predicate<TElement>

        Optional predicate that determines which elements are counted. When omitted, every element is considered a match.

      Returns boolean

      true when at least count matching elements are present; otherwise, false.

      Thrown when count is negative.

      Re-throws any error encountered while iterating the sequence or executing the predicate.

      Enumeration stops as soon as the required number of matches is found, avoiding unnecessary work on long sequences.

      const numbers = from([1, 2, 3, 4, 5]);
      const hasAtLeastTwoEvens = numbers.atLeast(2, n => n % 2 === 0);
      console.log(hasAtLeastTwoEvens); // true
    • Determines whether the sequence contains no more than count elements that satisfy the optional predicate.

      Parameters

      • count: number

        Maximum number of matching elements allowed. Must be greater than or equal to 0.

      • Optionalpredicate: Predicate<TElement>

        Optional predicate that determines which elements are counted. When omitted, every element is considered a match.

      Returns boolean

      true when the number of matching elements does not exceed count; otherwise, false.

      Thrown when count is negative.

      Re-throws any error encountered while iterating the sequence or executing the predicate.

      Enumeration stops as soon as the count is exceeded, making it efficient for large or infinite sequences.

      const numbers = from([1, 2, 3, 4, 5]);
      const hasAtMostOneEven = numbers.atMost(1, n => n % 2 === 0);
      console.log(hasAtMostOneEven); // false
    • Computes the arithmetic mean of the numeric values produced for each element in the sequence.

      Parameters

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element. Defaults to the element itself.

      Returns number

      The arithmetic mean of the selected values.

      Thrown when the sequence is empty.

      Provide a selector when the elements are not already numeric. All values are enumerated exactly once.

      const numbers = from([1, 2, 3, 4, 5]);
      const avg = numbers.average();
      console.log(avg); // 3

      const people = from([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Charlie', age: 35 },
      ]);
      const avgAge = people.average(p => p.age);
      console.log(avgAge); // 30
    • Produces the cartesian product between this sequence and iterable.

      Type Parameters

      • TSecond

        Type of elements emitted by iterable.

      Parameters

      • iterable: Iterable<TSecond>

        The secondary sequence paired with every element from the source.

      Returns IEnumerable<[TElement, TSecond]>

      A deferred sequence that yields each ordered pair [source, other].

      Re-throws any error raised while iterating the source or iterable.

      The secondary sequence is fully buffered before iteration starts so that it can be replayed for every source element. The resulting sequence stops when the source sequence completes.

      const pairs = from([1, 2]).cartesian(['A', 'B']).toArray();
      console.log(pairs); // [[1, 'A'], [1, 'B'], [2, 'A'], [2, 'B']]
    • Reinterprets each element in the sequence as the specified result type.

      Type Parameters

      • TResult

        Target type exposed by the returned sequence.

      Returns IEnumerable<TResult>

      A sequence that yields the same elements typed as TResult.

      No runtime conversion occurs; ensure the underlying elements are compatible with TResult to avoid downstream failures.

      const mixed = from([1, 'two', 3, 'four']);
      const numbers = mixed.cast<number>().where(x => typeof x === 'number');
      console.log(numbers.toArray()); // [1, 3]
    • Splits the sequence into contiguous subsequences containing at most the specified number of elements.

      Parameters

      • size: number

        Maximum number of elements to include in each chunk. Must be greater than 0.

      Returns IEnumerable<IEnumerable<TElement>>

      A sequence where each element is a chunk of the original sequence.

      Thrown when size is less than 1.

      The final chunk may contain fewer elements than size. Enumeration is deferred until the returned sequence is iterated.

      const numbers = from([1, 2, 3, 4, 5, 6, 7, 8]);
      const chunks = numbers.chunk(3);
      console.log(chunks.select(c => c.toArray()).toArray()); // [[1, 2, 3], [4, 5, 6], [7, 8]]
    • Generates the unique combinations that can be built from the elements in the sequence.

      Parameters

      • Optionalsize: number

        Optional number of elements that each combination must contain. When omitted, combinations of every possible length are produced.

      Returns IEnumerable<IEnumerable<TElement>>

      A sequence of combinations built from the source elements.

      Thrown when size is negative.

      The source sequence is materialised before combinations are produced, so very large inputs can be expensive. Duplicate combinations produced by repeated elements are emitted only once.

      const numbers = from([1, 2, 3]);
      const combs = numbers.combinations(2);
      console.log(combs.select(c => c.toArray()).toArray()); // [[1, 2], [1, 3], [2, 3]]
    • Filters out null and undefined values from the sequence.

      Returns IEnumerable<NonNullable<TElement>>

      A sequence containing only the elements that are neither null nor undefined.

      The method preserves other falsy values (such as 0 or an empty string) and defers execution until the returned sequence is iterated.

      const values = from([1, null, 0, undefined]).compact().toArray();
      console.log(values); // [1, 0]
    • Appends the specified iterable to the end of the sequence.

      Parameters

      • iterable: Iterable<TElement>

        Additional elements that are yielded after the current sequence.

      Returns IEnumerable<TElement>

      A sequence containing the elements of the current sequence followed by those from iterable.

      Enumeration of both sequences is deferred until the result is iterated.

      const numbers1 = from([1, 2, 3]);
      const numbers2 = [4, 5, 6];
      const concatenated = numbers1.concat(numbers2).toArray();
      console.log(concatenated); // [1, 2, 3, 4, 5, 6]
    • Determines whether the sequence contains a specific element using an optional comparator.

      Parameters

      • element: TElement

        Element to locate in the sequence.

      • Optionalcomparator: EqualityComparator<TElement, TElement>

        Optional equality comparator used to match elements. Defaults to the library's standard equality comparison.

      Returns boolean

      true when the element is found; otherwise, false.

      const numbers = from([1, 2, 3, 4, 5]);
      const hasThree = numbers.contains(3);
      console.log(hasThree); // true

      const hasTen = numbers.contains(10);
      console.log(hasTen); // false
    • Check if this collection contains all the elements of the given collection.

      Type Parameters

      • TSource

      Parameters

      • collection: Iterable<TSource>

        The collection whose element will be tested for existence against this collection.

      Returns boolean

      true if this collection contains all the elements from the given collection, false otherwise.

    • Computes the Pearson correlation coefficient between this sequence and iterable.

      Type Parameters

      • TSecond

        Type of elements produced by iterable.

      Parameters

      • iterable: Iterable<TSecond>

        Sequence whose elements align by index with the source sequence.

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element of the source sequence. Defaults to treating the element itself as numeric.

      • OptionalotherSelector: Selector<TSecond, number>

        Optional projection that extracts the numeric value for each element of iterable. Defaults to treating the element itself as numeric.

      Returns number

      The correlation coefficient in the interval [-1, 1].

      Thrown when the sequences do not contain the same number of elements.

      Thrown when fewer than two aligned pairs are available.

      Thrown when the standard deviation of either numeric projection is zero.

      Re-throws any error encountered while iterating the sequences or executing the selector projections.

      Both sequences are consumed simultaneously via an online algorithm that avoids buffering the full dataset. Ensure the iterables are aligned because mismatch detection occurs only after iteration begins.

      const temperatures = from([15, 18, 21, 24]);
      const sales = [30, 36, 42, 48];
      const correlation = temperatures.correlation(sales);
      console.log(correlation); // 1
    • Computes the Pearson correlation coefficient between two numeric projections of the sequence.

      Parameters

      • leftSelector: Selector<TElement, number>

        Projection that produces the first numeric series for each element.

      • rightSelector: Selector<TElement, number>

        Projection that produces the second numeric series for each element.

      Returns number

      The correlation coefficient in the interval [-1, 1].

      Thrown when fewer than two elements are available.

      Thrown when the standard deviation of either numeric projection is zero.

      Re-throws any error encountered while iterating the sequence or executing the selector projections.

      The sequence is consumed exactly once using an online algorithm, which keeps memory usage constant even for large inputs.

      const metrics = from([
      { impressions: 1_000, clicks: 50 },
      { impressions: 1_500, clicks: 75 },
      { impressions: 2_000, clicks: 100 }
      ]);
      const correlation = metrics.correlationBy(m => m.impressions, m => m.clicks);
      console.log(correlation); // 1
    • Counts the number of elements in the sequence, optionally restricted by a predicate.

      Parameters

      • Optionalpredicate: Predicate<TElement>

        Optional predicate that determines which elements are counted. When omitted, all elements are counted.

      Returns number

      The number of elements that satisfy the predicate.

      Prefer calling any() to test for existence instead of comparing this result with zero.

      const numbers = from([1, 2, 3, 4, 5]);
      const totalCount = numbers.count();
      console.log(totalCount); // 5

      const evenCount = numbers.count(x => x % 2 === 0);
      console.log(evenCount); // 2
    • Counts the occurrences of elements grouped by a derived key.

      Type Parameters

      • TKey

        Type produced by keySelector.

      Parameters

      • keySelector: Selector<TElement, TKey>

        Selector used to derive the grouping key for each element.

      • Optionalcomparator: EqualityComparator<TKey, TKey>

        Optional equality comparator used to match keys. Defaults to the library's standard equality comparison.

      Returns IEnumerable<KeyValuePair<TKey, number>>

      A sequence of key/count pairs describing how many elements share each key.

      Each key appears exactly once in the result with its associated occurrence count.

      const products = from([
      { name: 'Apple', category: 'Fruit' },
      { name: 'Banana', category: 'Fruit' },
      { name: 'Carrot', category: 'Vegetable' },
      ]);

      const countByCategory = products.countBy(p => p.category).toArray();
      console.log(countByCategory);
      // [
      // { key: 'Fruit', value: 2 },
      // { key: 'Vegetable', value: 1 }
      // ]
    • Calculates the covariance between this sequence and iterable.

      Type Parameters

      • TSecond

        Type of elements produced by iterable.

      Parameters

      • iterable: Iterable<TSecond>

        Sequence whose elements align by index with the source sequence.

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element of the source sequence. Defaults to treating the element itself as numeric.

      • OptionalotherSelector: Selector<TSecond, number>

        Optional projection that extracts the numeric value for each element of iterable. Defaults to treating the element itself as numeric.

      • Optionalsample: boolean

        When true, computes the sample covariance dividing by n - 1; when false, computes the population covariance dividing by n. Defaults to true.

      Returns number

      The calculated covariance.

      Thrown when the sequences do not contain the same number of elements.

      Thrown when fewer than two aligned pairs are available.

      Re-throws any error thrown while iterating either sequence or executing the selector projections.

      Both sequences are consumed simultaneously so streaming statistics can be computed without materialising all elements. Ensure the iterables are aligned because mismatch detection occurs only after iteration begins.

      const numbers = from([1, 2, 3, 4, 5]);
      const doubles = [2, 4, 6, 8, 10];
      const covariance = numbers.covariance(doubles);
      console.log(covariance); // 5
    • Calculates the covariance between two numeric projections of the sequence.

      Parameters

      • leftSelector: Selector<TElement, number>

        Projection that produces the first numeric series for each element.

      • rightSelector: Selector<TElement, number>

        Projection that produces the second numeric series for each element.

      • Optionalsample: boolean

        When true, computes the sample covariance dividing by n - 1; when false, computes the population covariance dividing by n. Defaults to true.

      Returns number

      The calculated covariance.

      Thrown when fewer than two elements are available.

      Re-throws any error thrown while iterating the sequence or executing the selector projections.

      The sequence is consumed exactly once using an online algorithm that avoids buffering, making it suitable for large datasets.

      const metrics = from([
      { x: 1, y: 2 },
      { x: 2, y: 4 },
      { x: 3, y: 6 }
      ]);
      const covariance = metrics.covarianceBy(p => p.x, p => p.y);
      console.log(covariance); // 2
    • Repeats the sequence the specified number of times, or indefinitely when no count is provided.

      Parameters

      • Optionalcount: number

        Optional number of times to repeat the sequence. When omitted, the sequence repeats without end.

      Returns IEnumerable<TElement>

      A sequence that yields the original elements cyclically.

      Thrown when the sequence is empty.

      When count is undefined, consume the result with care because it represents an infinite sequence.

      const numbers = from([1, 2, 3]);
      const cycled = numbers.cycle(2).toArray();
      console.log(cycled); // [1, 2, 3, 1, 2, 3]
    • Supplies fallback content when the sequence contains no elements.

      Parameters

      • Optionalvalue: TElement | null

        Optional value returned in a singleton sequence when the source is empty. Defaults to null.

      Returns IEnumerable<TElement | null>

      The original sequence when it has elements; otherwise, a singleton sequence containing the provided value.

      Use this to ensure downstream operators always receive at least one element.

      const empty = from([]);
      const withDefault = empty.defaultIfEmpty(0).toArray();
      console.log(withDefault); // [0]

      const numbers = from([1, 2, 3]);
      const withDefault2 = numbers.defaultIfEmpty(0).toArray();
      console.log(withDefault2); // [1, 2, 3]
    • Determines whether the sequence and iterable share no equivalent elements.

      Type Parameters

      • TSecond

        Type of elements yielded by iterable.

      Parameters

      Returns boolean

      true when the sequences are disjoint; otherwise, false.

      Re-throws any error encountered while iterating the source, iterable, or executing the comparator.

      When the default comparator is used, the method buffers the source elements in a Set so it can short-circuit as soon as a shared element is detected. With a custom comparator, the method compares every pair of elements, which may iterate each sequence multiple times; prefer the default comparator when possible for better performance.

      const first = from([1, 2, 3]);
      const second = [4, 5, 6];
      const areDisjoint = first.disjoint(second);
      console.log(areDisjoint); // true
    • Determines whether the key projections of the sequence and iterable are mutually exclusive.

      Type Parameters

      Parameters

      Returns boolean

      true when no projected keys intersect; otherwise, false.

      Re-throws any error encountered while iterating either sequence or executing the selector projections/comparator.

      When the default comparator is used, the method buffers the larger key collection in a Set and short-circuits as soon as an intersecting key is found. Providing a custom comparator forces a full pairwise comparison, which may iterate both sequences repeatedly; prefer the default comparator when suitable.

      const left = from([{ name: 'Alice' }, { name: 'Bella' }]);
      const right = [{ name: 'Mel' }];
      const areDisjoint = left.disjointBy(right, p => p.name, p => p.name);
      console.log(areDisjoint); // true
    • Eliminates duplicate elements from the sequence using an optional comparator.

      Parameters

      • OptionalkeyComparator: EqualityComparator<TElement, TElement>

        Optional equality comparator used to determine whether two elements are identical. Defaults to the library's standard equality comparison.

      Returns IEnumerable<TElement>

      A sequence that yields each distinct element once.

      Elements are compared by value; when using custom types, provide an appropriate comparator to avoid reference-based comparisons.

      const numbers = from([1, 2, 2, 3, 1, 4, 5, 5]);
      const distinctNumbers = numbers.distinct().toArray();
      console.log(distinctNumbers); // [1, 2, 3, 4, 5]
    • Eliminates duplicate elements by comparing keys computed for each element.

      Type Parameters

      • TKey

        Key type returned by keySelector.

      Parameters

      • keySelector: Selector<TElement, TKey>

        Selector used to project each element to the key used for distinctness.

      • OptionalkeyComparator: EqualityComparator<TKey, TKey>

        Optional equality comparator used to compare keys. Defaults to the library's standard equality comparison.

      Returns IEnumerable<TElement>

      A sequence that contains the first occurrence of each unique key.

      When keys are expensive to compute, consider memoisation because each element's key is evaluated exactly once.

      const products = from([
      { name: 'Apple', category: 'Fruit' },
      { name: 'Banana', category: 'Fruit' },
      { name: 'Carrot', category: 'Vegetable' },
      ]);

      const distinctByCategory = products.distinctBy(p => p.category).toArray();
      console.log(distinctByCategory);
      // [
      // { name: 'Apple', category: 'Fruit' },
      // { name: 'Carrot', category: 'Vegetable' }
      // ]
    • Removes consecutive duplicate elements by comparing keys projected from each element.

      Type Parameters

      • TKey

        Key type returned by keySelector.

      Parameters

      • keySelector: Selector<TElement, TKey>

        Selector used to project each element to the key used for comparison.

      • OptionalkeyComparator: EqualityComparator<TKey, TKey>

        Optional equality comparator used to compare keys. Defaults to the library's standard equality comparison.

      Returns IEnumerable<TElement>

      A sequence that yields the first element in each run of elements whose keys change.

      Enumeration stops comparing elements once a different key is encountered, making this useful for collapsing grouped data.

      const products = from([
      { name: 'Apple', category: 'Fruit' },
      { name: 'Banana', category: 'Fruit' },
      { name: 'Carrot', category: 'Vegetable' },
      { name: 'Broccoli', category: 'Vegetable' },
      { name: 'Orange', category: 'Fruit' },
      ]);

      const distinctByCategory = products.distinctUntilChangedBy(p => p.category).toArray();
      console.log(distinctByCategory);
      // [
      // { name: 'Apple', category: 'Fruit' },
      // { name: 'Carrot', category: 'Vegetable' },
      // { name: 'Orange', category: 'Fruit' }
      // ]
    • Retrieves the element at the specified zero-based index.

      Parameters

      • index: number

        Zero-based position of the element to retrieve.

      Returns TElement

      The element located at the requested index.

      Thrown when index is negative or greater than or equal to the number of elements in the sequence.

      Enumeration stops once the requested element is found; remaining elements are not evaluated.

      const numbers = from([1, 2, 3, 4, 5]);
      const element = numbers.elementAt(2);
      console.log(element); // 3
    • Retrieves the element at the specified zero-based index or returns null when the index is out of range.

      Parameters

      • index: number

        Zero-based position of the element to retrieve.

      Returns TElement | null

      The element at index, or null when the sequence is shorter than index + 1 or when index is negative.

      Use this overload when out-of-range access should produce a sentinel value instead of throwing an exception.

      const numbers = from([1, 2, 3, 4, 5]);
      const element = numbers.elementAtOrDefault(2);
      console.log(element); // 3

      const element2 = numbers.elementAtOrDefault(10);
      console.log(element2); // null
    • Determines whether the sequence contains exactly count elements that satisfy the optional predicate.

      Parameters

      • count: number

        Exact number of matching elements required. Must be greater than or equal to 0.

      • Optionalpredicate: Predicate<TElement>

        Optional predicate that determines which elements are counted. When omitted, every element is considered a match.

      Returns boolean

      true when exactly count matching elements are present; otherwise, false.

      Thrown when count is negative.

      Re-throws any error encountered while iterating the sequence or executing the predicate.

      Enumeration stops once the running total exceeds count, preventing unnecessary work on long sequences.

      const numbers = from([1, 2, 3, 4, 5]);
      const hasExactlyThreeOdds = numbers.exactly(3, n => n % 2 !== 0);
      console.log(hasExactlyThreeOdds); // true
    • Returns the elements of this sequence whose projected keys are not present in the specified iterable.

      Type Parameters

      • TKey

        Type produced by keySelector.

      Parameters

      • iterable: Iterable<TElement>

        Sequence whose elements define the keys that should be excluded.

      • keySelector: Selector<TElement, TKey>

        Selector used to project each element to the key used for comparison.

      • OptionalkeyComparator: EqualityComparator<TKey, TKey> | OrderComparator<TKey, TKey>

        Optional comparator used to compare keys. Both equality and order comparators are supported; defaults to the library's standard equality comparison when omitted.

      Returns IEnumerable<TElement>

      A sequence that contains the elements from this sequence whose keys are absent from iterable.

      Source ordering is preserved and duplicate elements with distinct keys remain. The exclusion keys are materialised by fully enumerating iterable.

      const products1 = from([
      { name: 'Apple', category: 'Fruit' },
      { name: 'Banana', category: 'Fruit' },
      { name: 'Carrot', category: 'Vegetable' },
      ]);
      const products2 = [
      { name: 'Broccoli', category: 'Vegetable' },
      ];

      const result = products1.exceptBy(products2, p => p.category).toArray();
      console.log(result);
      // [
      // { name: 'Apple', category: 'Fruit' },
      // { name: 'Banana', category: 'Fruit' }
      // ]
    • Returns the first element that satisfies the provided type guard.

      Type Parameters

      • TFiltered

        Subtype confirmed by the type guard.

      Parameters

      Returns TFiltered

      The first element that satisfies the type guard.

      Thrown when the sequence is empty.

      Thrown when no element satisfies the type guard.

      Enumeration stops immediately once a matching element is found.

      const numbers = from([1, 2, 3, 4, 5]);
      const firstElement = numbers.first();
      console.log(firstElement); // 1

      const firstEven = numbers.first(x => x % 2 === 0);
      console.log(firstEven); // 2
    • Returns the first element in the sequence, optionally filtered by a predicate.

      Parameters

      • Optionalpredicate: Predicate<TElement>

        Predicate evaluated against each element; when omitted, the first element is returned.

      Returns TElement

      The first element of the sequence that satisfies the predicate (or the very first element when none is provided).

      Thrown when the sequence is empty.

      Thrown when a predicate is supplied and no element satisfies it.

      Enumeration stops immediately once a matching element is found.

    • Returns the first element that satisfies the provided type guard, or null when no such element exists.

      Type Parameters

      • TFiltered

        Subtype confirmed by the type guard.

      Parameters

      Returns TFiltered | null

      The first element that satisfies the type guard, or null when none match.

      Enumeration stops immediately once a matching element is found.

      const numbers = from([1, 2, 3, 4, 5]);
      const firstElement = numbers.firstOrDefault();
      console.log(firstElement); // 1

      const firstEven = numbers.firstOrDefault(x => x % 2 === 0);
      console.log(firstEven); // 2

      const empty = from<number>([]);
      const firstOfEmpty = empty.firstOrDefault();
      console.log(firstOfEmpty); // null

      const noEvens = from([1, 3, 5]);
      const firstEven2 = noEvens.firstOrDefault(x => x % 2 === 0);
      console.log(firstEven2); // null
    • Returns the first element in the sequence or null when the sequence is empty or no element satisfies the predicate.

      Parameters

      • Optionalpredicate: Predicate<TElement>

        Predicate evaluated against each element; when omitted, the first element is returned.

      Returns TElement | null

      The first matching element, or null when no match is found.

      This method never throws; it communicates absence through the null return value.

    • Partitions the sequence into groups based on keys projected from each element.

      Type Parameters

      Parameters

      • keySelector: Selector<TElement, TKey>

        Selector used to derive the grouping key for each element.

      • OptionalkeyComparator: EqualityComparator<TKey, TKey>

        Optional equality comparator used to match keys. Defaults to the library's standard equality comparison.

      Returns IEnumerable<IGroup<TKey, TElement>>

      A sequence of groups, each exposing the key and the elements that share it.

      The source sequence is enumerated once when the result is iterated. Elements within each group preserve their original order, and group contents are cached for repeated enumeration.

      const products = from([
      { name: 'Apple', category: 'Fruit' },
      { name: 'Banana', category: 'Fruit' },
      { name: 'Carrot', category: 'Vegetable' },
      ]);

      const grouped = products.groupBy(p => p.category);
      for (const group of grouped) {
      console.log(group.key, group.toArray());
      }
      // Fruit [ { name: 'Apple', category: 'Fruit' }, { name: 'Banana', category: 'Fruit' } ]
      // Vegetable [ { name: 'Carrot', category: 'Vegetable' } ]
    • Correlates each element of the sequence with a collection of matching elements from another sequence.

      Type Parameters

      • TInner

        Type of elements in the inner sequence.

      • TKey

        Type of key produced by the key selectors.

      • TResult

        Type of element returned by resultSelector.

      Parameters

      • innerEnumerable: IEnumerable<TInner>

        Sequence whose elements are grouped and joined with the outer elements.

      • outerKeySelector: Selector<TElement, TKey>

        Selector that extracts the join key from each outer element.

      • innerKeySelector: Selector<TInner, TKey>

        Selector that extracts the join key from each inner element.

      • resultSelector: JoinSelector<TElement, IEnumerable<TInner>, TResult>

        Projection that combines an outer element with an IEnumerable of matching inner elements.

      • OptionalkeyComparator: EqualityComparator<TKey, TKey>

        Optional equality comparator used to match keys. Defaults to the library's standard equality comparison.

      Returns IEnumerable<TResult>

      A sequence produced by applying resultSelector to each outer element and its matching inner elements.

      The inner sequence is enumerated once to build an in-memory lookup before outer elements are processed. Each outer element is then evaluated lazily and preserves the original outer ordering.

      const categories = from([
      { id: 1, name: 'Fruit' },
      { id: 2, name: 'Vegetable' },
      ]);
      const products = from([
      { name: 'Apple', categoryId: 1 },
      { name: 'Banana', categoryId: 1 },
      { name: 'Carrot', categoryId: 2 },
      ]);

      const joined = categories.groupJoin(
      products,
      c => c.id,
      p => p.categoryId,
      (c, ps) => ({ ...c, products: ps.toArray() })
      ).toArray();

      console.log(joined);
      // [
      // { id: 1, name: 'Fruit', products: [ { name: 'Apple', categoryId: 1 }, { name: 'Banana', categoryId: 1 } ] },
      // { id: 2, name: 'Vegetable', products: [ { name: 'Carrot', categoryId: 2 } ] }
      // ]
    • Enumerates the sequence while exposing the zero-based index alongside each element.

      Returns IEnumerable<[number, TElement]>

      A sequence of [index, element] tuples.

      The index is assigned in the order elements are produced. Enumeration is deferred until the result is iterated.

      const letters = from(['a', 'b', 'c']);
      const indexed = letters.index().toArray();
      console.log(indexed); // [[0, 'a'], [1, 'b'], [2, 'c']]
    • Interleaves the sequence with another iterable, yielding elements in alternating order.

      Type Parameters

      • TSecond

        Type of elements in the second iterable.

      Parameters

      • iterable: Iterable<TSecond>

        Iterable whose elements are alternated with the current sequence.

      Returns IEnumerable<TElement | TSecond>

      A sequence that alternates between elements from this sequence and iterable.

      If one sequence is longer, the remaining elements are appended after the shorter sequence is exhausted. Enumeration is deferred.

      const numbers1 = from([1, 3, 5]);
      const numbers2 = [2, 4, 6];
      const interleaved = numbers1.interleave(numbers2).toArray();
      console.log(interleaved); // [1, 2, 3, 4, 5, 6]
    • Returns the elements whose keys are common to this sequence and the specified iterable.

      Type Parameters

      Parameters

      • iterable: Iterable<TElement>

        Sequence whose elements define the keys considered part of the intersection.

      • keySelector: Selector<TElement, TKey>

        Selector used to project each element to the key used for comparison.

      • OptionalkeyComparator: EqualityComparator<TKey, TKey> | OrderComparator<TKey, TKey>

        Optional comparator used to compare keys. Both equality and order comparators are supported; defaults to the library's standard equality comparison when omitted.

      Returns IEnumerable<TElement>

      A sequence containing the intersection of the two sequences based on matching keys.

      The iterable is fully enumerated to materialise the inclusion keys before yielding results. Source ordering is preserved.

      const products1 = from([
      { name: 'Apple', category: 'Fruit' },
      { name: 'Carrot', category: 'Vegetable' },
      ]);
      const products2 = [
      { name: 'Banana', category: 'Fruit' },
      { name: 'Broccoli', category: 'Vegetable' },
      ];

      const result = products1.intersectBy(products2, p => p.category).toArray();
      console.log(result);
      // [
      // { name: 'Apple', category: 'Fruit' },
      // { name: 'Carrot', category: 'Vegetable' }
      // ]
    • Produces a projection from the sequence and a second sequence by matching elements that share an identical join key.

      Type Parameters

      • TInner

        Type of elements in the inner sequence.

      • TKey

        Type of key produced by the key selectors.

      • TResult

        Type of element returned by resultSelector.

      Parameters

      • innerEnumerable: IEnumerable<TInner>

        Sequence whose elements are joined with the outer sequence.

      • outerKeySelector: Selector<TElement, TKey>

        Selector that extracts the join key from each outer element.

      • innerKeySelector: Selector<TInner, TKey>

        Selector that extracts the join key from each inner element.

      • resultSelector: JoinSelector<TElement, TInner, TResult>

        Projection that combines an outer element with a matching inner element.

      • OptionalkeyComparator: EqualityComparator<TKey, TKey>

        Optional equality comparator used to match keys. Defaults to the library's standard equality comparison when omitted.

      Returns IEnumerable<TResult>

      A sequence generated by applying resultSelector to each matching pair.

      The inner sequence is fully enumerated to build an in-memory lookup before outer elements are processed. The outer sequence is then enumerated lazily and its original ordering is preserved. This is an inner join; unmatched outer or inner elements are not emitted.

      const categories = from([
      { id: 1, name: 'Fruit' },
      { id: 2, name: 'Vegetable' },
      ]);
      const products = from([
      { name: 'Apple', categoryId: 1 },
      { name: 'Banana', categoryId: 1 },
      { name: 'Carrot', categoryId: 2 },
      ]);

      const joined = categories.join(
      products,
      c => c.id,
      p => p.categoryId,
      (c, p) => ({ category: c.name, product: p.name })
      ).toArray();

      console.log(joined);
      // [
      // { category: 'Fruit', product: 'Apple' },
      // { category: 'Fruit', product: 'Banana' },
      // { category: 'Vegetable', product: 'Carrot' }
      // ]
    • Returns the last element that satisfies the provided type guard.

      Type Parameters

      • TFiltered

        Subtype confirmed by the type guard.

      Parameters

      • predicate: TypePredicate<TElement, TFiltered>

        Type guard evaluated against each element. Every matching element becomes a candidate, and the final match is returned.

      Returns TFiltered

      The last element that satisfies the type guard.

      Thrown when the sequence is empty.

      Thrown when no element satisfies the type guard.

      The entire sequence is enumerated to locate the final match.

      const numbers = from([1, 2, 3, 4, 5]);
      const lastElement = numbers.last();
      console.log(lastElement); // 5

      const lastEven = numbers.last(x => x % 2 === 0);
      console.log(lastEven); // 4
    • Returns the last element in the sequence, optionally filtered by a predicate.

      Parameters

      • Optionalpredicate: Predicate<TElement>

        Predicate evaluated against each element. When omitted, the last element of the sequence is returned.

      Returns TElement

      The last element that satisfies the predicate (or the final element when no predicate is supplied).

      Thrown when the sequence is empty.

      Thrown when a predicate is supplied and no element satisfies it.

      The entire sequence is enumerated to locate the final match.

    • Returns the last element that satisfies the provided type guard, or null when no such element exists.

      Type Parameters

      • TFiltered

        Subtype confirmed by the type guard.

      Parameters

      • predicate: TypePredicate<TElement, TFiltered>

        Type guard evaluated against each element. Every matching element becomes a candidate, and the final match is returned.

      Returns TFiltered | null

      The last element that satisfies the type guard, or null when none match.

      The entire sequence is enumerated to locate the final match. This overload never throws; it communicates absence through the null return value.

      const numbers = from([1, 2, 3, 4, 5]);
      const lastElement = numbers.lastOrDefault();
      console.log(lastElement); // 5

      const lastEven = numbers.lastOrDefault(x => x % 2 === 0);
      console.log(lastEven); // 4

      const empty = from<number>([]);
      const lastOfEmpty = empty.lastOrDefault();
      console.log(lastOfEmpty); // null

      const noEvens = from([1, 3, 5]);
      const lastEven2 = noEvens.lastOrDefault(x => x % 2 === 0);
      console.log(lastEven2); // null
    • Returns the last element in the sequence or null when the sequence is empty or no element satisfies the predicate.

      Parameters

      • Optionalpredicate: Predicate<TElement>

        Predicate evaluated against each element. When omitted, the last element of the sequence is returned.

      Returns TElement | null

      The last element that satisfies the predicate, or null when no match is found.

      The entire sequence is enumerated to locate the final match. This overload never throws; it communicates absence through the null return value.

    • Produces a projection from the sequence and a second sequence by matching elements that share an identical join key. Outer elements with no match are included once with null as the inner value.

      Type Parameters

      • TInner

        Type of elements within the inner sequence.

      • TKey

        Type of key produced by the key selectors.

      • TResult

        Type of element returned by resultSelector.

      Parameters

      • innerEnumerable: IEnumerable<TInner>

        Sequence whose elements are joined with the outer sequence.

      • outerKeySelector: Selector<TElement, TKey>

        Selector that extracts the join key from each outer element.

      • innerKeySelector: Selector<TInner, TKey>

        Selector that extracts the join key from each inner element.

      • resultSelector: JoinSelector<TElement, TInner, TResult>

        Projection that combines an outer element with a matching inner element. When no match exists, null is supplied as the inner value.

      • OptionalkeyComparator: EqualityComparator<TKey, TKey>

        Optional equality comparator used to match keys. Defaults to the library's standard equality comparison when omitted.

      Returns IEnumerable<TResult>

      A sequence generated by applying resultSelector to each matching pair (and unmatched outer elements).

      The inner sequence is fully enumerated to build an in-memory lookup before outer elements are processed. The outer sequence is then enumerated lazily and its original ordering is preserved. This is a left outer join.

      const schools = from([
      { id: 1, name: 'Elementary School' },
      { id: 2, name: 'High School' }
      ]);
      const students = from([
      { name: 'Dana', schoolId: 1 },
      { name: 'Sam', schoolId: 3 }
      ]);

      const joined = schools.leftJoin(
      students,
      s => s.id,
      st => st.schoolId,
      (school, student) => ({ school: school.name, student: student?.name ?? null })
      ).toArray();

      console.log(joined);
      // [
      // { school: 'Elementary School', student: 'Dana' },
      // { school: 'High School', student: null }
      // ]
    • Returns the largest numeric value produced for the elements in the sequence.

      Parameters

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element. Defaults to the element itself.

      Returns number

      The maximum of the projected values.

      Thrown when the sequence is empty.

      The entire sequence is enumerated exactly once. Provide a selector when the elements are not already numeric.

      const numbers = from([1, 5, 2, 4, 3]);
      const maxNumber = numbers.max();
      console.log(maxNumber); // 5

      const people = from([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Charlie', age: 28 },
      ]);
      const maxAge = people.max(p => p.age);
      console.log(maxAge); // 30
    • Returns the element whose projected key is greatest according to the provided comparator.

      Type Parameters

      Parameters

      • keySelector: Selector<TElement, TKey>

        Selector used to project each element to the key used for comparison.

      • Optionalcomparator: OrderComparator<TKey, TKey>

        Optional order comparator used to compare keys. Defaults to the library's standard order comparison when omitted.

      Returns TElement

      The element whose key is maximal.

      Thrown when the sequence is empty.

      When multiple elements share the maximal key, the first such element in the sequence is returned.

      const people = from([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Charlie', age: 28 },
      ]);
      const oldestPerson = people.maxBy(p => p.age);
      console.log(oldestPerson); // { name: 'Bob', age: 30 }
    • Calculates the median of the numeric values produced by the sequence.

      Parameters

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element. Defaults to treating the element itself as numeric.

      • Optionaltie: MedianTieStrategy

        Determines how the median is resolved when the sequence contains an even number of elements. Defaults to "interpolate", which averages the two central values. Specify "low" or "high" to select the lower or higher neighbour respectively.

      Returns number

      The calculated median, or NaN when the sequence contains no elements.

      Re-throws any error thrown while iterating the sequence or executing selector.

      The sequence is enumerated once and buffered so a selection algorithm can locate the middle element(s) without fully sorting. Supply selector when the elements are not already numeric.

      const medianValue = from([1, 5, 2, 4, 3]).median();
      console.log(medianValue); // 3

      const people = from([
      { name: 'Alice', age: 23 },
      { name: 'Bella', age: 21 },
      { name: 'Mirei', age: 22 },
      { name: 'Hanna', age: 20 },
      { name: 'Noemi', age: 29 }
      ]);
      const medianAge = people.median(p => p.age);
      console.log(medianAge); // 22
    • Returns the smallest numeric value produced for the elements in the sequence.

      Parameters

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element. Defaults to the element itself.

      Returns number

      The minimum of the projected values.

      Thrown when the sequence is empty.

      The entire sequence is enumerated exactly once. Provide a selector when the elements are not already numeric.

      const numbers = from([3, 1, 5, 2, 4]);
      const minNumber = numbers.min();
      console.log(minNumber); // 1

      const people = from([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Charlie', age: 22 },
      ]);
      const minAge = people.min(p => p.age);
      console.log(minAge); // 22
    • Returns the element whose projected key is smallest according to the provided comparator.

      Type Parameters

      Parameters

      • keySelector: Selector<TElement, TKey>

        Selector used to project each element to the key used for comparison.

      • Optionalcomparator: OrderComparator<TKey, TKey>

        Optional order comparator used to compare keys. Defaults to the library's standard order comparison when omitted.

      Returns TElement

      The element whose key is minimal.

      Thrown when the sequence is empty.

      When multiple elements share the minimal key, the first such element in the sequence is returned.

      const people = from([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Charlie', age: 22 },
      ]);
      const youngestPerson = people.minBy(p => p.age);
      console.log(youngestPerson); // { name: 'Charlie', age: 22 }
    • Returns the element that appears most frequently in the sequence.

      Type Parameters

      Parameters

      • OptionalkeySelector: Selector<TElement, TKey>

        Optional selector that projects each element to the key used for frequency counting. Defaults to the element itself.

      Returns TElement

      The first element whose occurrence count matches the maximum frequency.

      Thrown when the sequence is empty.

      Re-throws any error thrown while iterating the sequence or executing keySelector.

      The source sequence is fully enumerated to build frequency counts before the result is determined. When multiple keys share the same frequency, the earliest corresponding element is returned.

      const winner = from([1, 2, 2, 3]).mode();
      console.log(winner); // 2
    • Returns the element that appears most frequently in the sequence, or null when the sequence is empty.

      Type Parameters

      Parameters

      • OptionalkeySelector: Selector<TElement, TKey>

        Optional selector that projects each element to the key used for frequency counting. Defaults to the element itself.

      Returns TElement | null

      The first most frequent element, or null when the sequence contains no elements.

      Re-throws any error thrown while iterating the sequence or executing keySelector.

      Unlike mode, this overload communicates the absence of elements by returning null. When multiple keys share the maximum frequency, the element that appears first is returned.

      const winner = from<number>([]).modeOrDefault();
      console.log(winner); // null
    • Produces the elements whose occurrence count is tied for the highest frequency in the sequence.

      Type Parameters

      Parameters

      • OptionalkeySelector: Selector<TElement, TKey>

        Optional selector that projects each element to the key used for frequency counting. Defaults to the element itself.

      Returns IEnumerable<TElement>

      A deferred sequence containing one representative element for each frequency mode.

      Re-throws any error thrown while iterating the sequence or executing keySelector.

      Enumeration of the result buffers the entire source to compute frequency counts before yielding results. When multiple elements share a key, only the first occurrence is emitted.

      const modes = from([1, 2, 2, 3, 3]).multimode().toArray();
      console.log(modes); // [2, 3]
    • Determines whether the sequence contains no elements that satisfy the optional predicate.

      Parameters

      • Optionalpredicate: Predicate<TElement>

        Optional predicate evaluated against each element. When omitted, the method returns true if the sequence is empty.

      Returns boolean

      true when no element satisfies the predicate (or when the sequence is empty and no predicate is provided); otherwise, false.

      This is more efficient than negating any with a predicate because iteration stops as soon as a matching element is found.

      const numbers = from([1, 3, 5]);
      const noEvens = numbers.none(x => x % 2 === 0);
      console.log(noEvens); // true

      const mixedNumbers = from([1, 2, 3, 5]);
      const noEvens2 = mixedNumbers.none(x => x % 2 === 0);
      console.log(noEvens2); // false
    • Filters the sequence, keeping only elements assignable to the specified type.

      Type Parameters

      • TResult extends ObjectType

        Type descriptor used to filter elements (constructor function or primitive type string).

      Parameters

      • type: TResult

        Type descriptor that determines which elements are retained.

      Returns IEnumerable<InferredType<TResult>>

      A sequence containing only the elements that match the specified type.

      This method performs a runtime type check for each element and yields matching elements lazily.

      const mixed = from([1, 'two', 3, 'four', new Date()]);
      const numbers = mixed.ofType('number').toArray();
      console.log(numbers); // [1, 3]

      const dates = mixed.ofType(Date).toArray();
      console.log(dates); // [Date object]
    • Sorts the elements of the sequence in ascending order based on keys projected from each element.

      Type Parameters

      Parameters

      • keySelector: Selector<TElement, TKey>

        Selector used to project each element to the key used for ordering.

      • Optionalcomparator: OrderComparator<TKey, TKey>

        Optional order comparator used to compare keys. Defaults to the library's standard order comparison when omitted.

      Returns IOrderedEnumerable<TElement>

      An ordered sequence that preserves the original relative ordering of elements that share the same key.

      Sorting is deferred; the sequence is ordered only when iterated. Use thenBy/thenByDescending on the returned sequence to specify secondary keys.

      const people = from([
      { name: 'Bob', age: 30 },
      { name: 'Alice', age: 25 },
      { name: 'Charlie', age: 22 },
      ]);
      const sorted = people.orderBy(p => p.age).toArray();
      console.log(sorted);
      // [
      // { name: 'Charlie', age: 22 },
      // { name: 'Alice', age: 25 },
      // { name: 'Bob', age: 30 }
      // ]
    • Sorts the elements of the sequence in descending order based on keys projected from each element.

      Type Parameters

      Parameters

      • keySelector: Selector<TElement, TKey>

        Selector used to project each element to the key used for ordering.

      • Optionalcomparator: OrderComparator<TKey, TKey>

        Optional order comparator used to compare keys. Defaults to the library's standard order comparison when omitted.

      Returns IOrderedEnumerable<TElement>

      An ordered sequence that preserves the original relative ordering of elements that share the same key while ordering keys descending.

      Sorting is deferred; the sequence is ordered only when iterated. Use thenBy/thenByDescending on the returned sequence to specify secondary keys.

      const people = from([
      { name: 'Charlie', age: 22 },
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      ]);
      const sorted = people.orderByDescending(p => p.age).toArray();
      console.log(sorted);
      // [
      // { name: 'Bob', age: 30 },
      // { name: 'Alice', age: 25 },
      // { name: 'Charlie', age: 22 }
      // ]
    • Calculates a percentile of the numeric values produced by the sequence.

      Parameters

      • percent: number

        Percentile expressed as a fraction between 0 and 1 where 0 corresponds to the minimum and 1 to the maximum.

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element. Defaults to treating the element itself as numeric.

      • Optionalstrategy: PercentileStrategy

        Strategy that determines how fractional ranks are resolved. Defaults to "linear", which interpolates between neighbouring values. Alternative strategies include "nearest", "low", "high", and "midpoint".

      Returns number

      The percentile value, or NaN when the sequence contains no elements.

      Re-throws any error thrown while iterating the sequence or executing selector.

      The sequence is enumerated once and buffered so the selection algorithm can determine the requested rank without fully sorting the data. When percent falls outside [0, 1], the result is clamped to the range implied by strategy.

      const upperQuartile = from([1, 2, 3, 4, 5]).percentile(0.75);
      console.log(upperQuartile); // 4

      const responseTimes = from([
      { endpoint: '/users', duration: 120 },
      { endpoint: '/users', duration: 80 },
      { endpoint: '/users', duration: 200 }
      ]);
      const p95 = responseTimes.percentile(0.95, r => r.duration, "nearest");
      console.log(p95); // 200
    • Generates permutations from the distinct elements of the sequence.

      Parameters

      • Optionalsize: number

        Optional target length for each permutation. When omitted, permutations use all distinct elements of the source.

      Returns IEnumerable<IEnumerable<TElement>>

      A lazy sequence of permutations, each materialised as an enumerable.

      Thrown when size is less than 1 or greater than the number of distinct elements.

      The source is enumerated to collect distinct elements before permutations are produced. Expect combinatorial growth in the number of permutations.

      const numbers = from([1, 2, 3]);
      const perms = numbers.permutations(2);
      console.log(perms.select(p => p.toArray()).toArray()); // [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
    • Applies a user-defined pipeline to this sequence and returns the operator's result.

      Type Parameters

      • TResult

        Result type produced by operator.

      Parameters

      Returns TResult

      The value produced by operator after optionally enumerating the sequence.

      Re-throws any error thrown by operator or during enumeration initiated by the operator.

      The operator controls when and how the sequence is iterated, enabling custom aggregations, projections, or interop with external APIs while preserving fluent syntax.

      const numbers = from([1, 2, 3, 4, 5]);
      const sum = numbers.pipe(e => e.sum());
      console.log(sum); // 15

      const filteredAndDoubled = numbers.pipe(e =>
      e.where(x => x % 2 === 0).select(x => x * 2).toArray()
      );
      console.log(filteredAndDoubled); // [4, 8]
    • Returns a deferred sequence that yields the supplied element before the source sequence.

      Parameters

      • element: TElement

        Element emitted before the original sequence.

      Returns IEnumerable<TElement>

      A sequence that yields element followed by the source elements.

      Enumeration is deferred; the source is not iterated until the resulting sequence is consumed.

      const numbers = from([1, 2, 3]);
      const prepended = numbers.prepend(0).toArray();
      console.log(prepended); // [0, 1, 2, 3]
    • Computes the multiplicative aggregate of the values produced for each element.

      Parameters

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element. Defaults to interpreting the element itself as a number.

      Returns number

      The product of all projected values.

      Thrown when the sequence is empty.

      The source is enumerated exactly once. Supply selector when elements are not already numeric.

      const numbers = from([1, 2, 3, 4, 5]);
      const result = numbers.product();
      console.log(result); // 120

      const people = from([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      ]);
      const ageProduct = people.product(p => p.age);
      console.log(ageProduct); // 750
    • Returns a deferred sequence that yields the source elements in reverse order.

      Returns IEnumerable<TElement>

      A sequence that produces the elements of the source in reverse iteration order.

      The implementation materialises the entire sequence into an array before emitting elements, so avoid using it on infinite sequences or when memory usage is a concern.

      const numbers = from([1, 2, 3, 4, 5]);
      const reversed = numbers.reverse().toArray();
      console.log(reversed); // [5, 4, 3, 2, 1]
    • Produces a projection from the sequence and a second sequence by matching elements that share an identical join key. Inner elements with no match are included once with null as the outer value.

      Type Parameters

      • TInner

        Type of elements within the inner sequence.

      • TKey

        Type of key produced by the key selectors.

      • TResult

        Type of element returned by resultSelector.

      Parameters

      • innerEnumerable: IEnumerable<TInner>

        Sequence whose elements are joined with the outer sequence.

      • outerKeySelector: Selector<TElement, TKey>

        Selector that extracts the join key from each outer element.

      • innerKeySelector: Selector<TInner, TKey>

        Selector that extracts the join key from each inner element.

      • resultSelector: JoinSelector<TElement | null, TInner, TResult>

        Projection that combines an outer element with a matching inner element. When no match exists, null is supplied as the outer value.

      • OptionalkeyComparator: EqualityComparator<TKey, TKey>

        Optional equality comparator used to match keys. Defaults to the library's standard equality comparison when omitted.

      Returns IEnumerable<TResult>

      A sequence generated by applying resultSelector to each matching pair (and unmatched inner elements).

      The outer sequence is fully enumerated to build an in-memory lookup before inner elements are processed. The inner sequence is then enumerated lazily and its original ordering is preserved. This is a right outer join.

      const schools = from([
      { id: 1, name: 'Elementary School' },
      { id: 2, name: 'High School' }
      ]);
      const students = from([
      { name: 'Dana', schoolId: 1 },
      { name: 'Sam', schoolId: 3 }
      ]);

      const joined = schools.rightJoin(
      students,
      s => s.id,
      st => st.schoolId,
      (school, student) => ({ school: school?.name ?? null, student: student.name })
      ).toArray();

      console.log(joined);
      // [
      // { school: 'Elementary School', student: 'Dana' },
      // { school: null, student: 'Sam' }
      // ]
    • Returns a deferred sequence that rotates the elements by the specified offset while preserving length.

      Parameters

      • shift: number

        Number of positions to rotate. Positive values move elements toward the end (left rotation); negative values move them toward the beginning (right rotation).

      Returns IEnumerable<TElement>

      A sequence containing the same elements shifted by the requested amount.

      The source is buffered sufficiently to honour the rotation. Rotation amounts larger than the sequence length are normalised by that length, so extremely large offsets may still require holding the entire sequence in memory.

      const numbers = from([1, 2, 3, 4, 5]);
      const rotated = numbers.rotate(2).toArray();
      console.log(rotated); // [3, 4, 5, 1, 2]

      const rotatedNegative = numbers.rotate(-2).toArray();
      console.log(rotatedNegative); // [4, 5, 1, 2, 3]
    • Produces a running aggregate of the sequence and yields each intermediate accumulator.

      Type Parameters

      Parameters

      • accumulator: Accumulator<TElement, TAccumulate>

        Function that combines the current accumulator value with the next element to produce the next accumulator.

      • Optionalseed: TAccumulate

        Optional initial accumulator. When omitted, the first element becomes the initial accumulator and is emitted as the first result.

      Returns IEnumerable<TAccumulate>

      A deferred sequence containing every intermediate accumulator produced by accumulator.

      Thrown when the sequence is empty and seed is not provided.

      The source is enumerated exactly once. When seed is supplied, it is not emitted; only accumulator results appear in the output.

      const numbers = from([1, 2, 3, 4, 5]);
      const runningTotal = numbers.scan((acc, x) => acc + x).toArray();
      console.log(runningTotal); // [1, 3, 6, 10, 15]
    • Projects each element and index into an iterable and flattens the results into a single sequence.

      Type Parameters

      • TResult

        Element type of the flattened sequence.

      Parameters

      Returns IEnumerable<TResult>

      A deferred sequence containing the concatenated contents of the iterables produced by selector.

      Each inner iterable is enumerated in order before moving to the next source element. Use this to expand one-to-many relationships.

      const lists = from([[1, 2], [3, 4], [5]]);
      const flattened = lists.selectMany(x => x).toArray();
      console.log(flattened); // [1, 2, 3, 4, 5]
    • Determines whether the sequence and another iterable contain equal elements in the same order.

      Parameters

      • iterable: Iterable<TElement>

        The iterable to compare against the source sequence.

      • Optionalcomparator: EqualityComparator<TElement, TElement>

        Optional equality comparator used to compare element pairs. Defaults to the library's standard equality comparator.

      Returns boolean

      true when both sequences have the same length and all corresponding elements are equal; otherwise, false.

      Enumeration stops as soon as a mismatch or length difference is observed. Both sequences are fully enumerated only when they are equal.

      const numbers1 = from([1, 2, 3]);
      const numbers2 = [1, 2, 3];
      const numbers3 = [1, 2, 4];

      const areEqual1 = numbers1.sequenceEqual(numbers2);
      console.log(areEqual1); // true

      const areEqual2 = numbers1.sequenceEqual(numbers3);
      console.log(areEqual2); // false
    • Returns a deferred sequence whose elements appear in random order.

      Returns IEnumerable<TElement>

      A sequence containing the same elements as the source but shuffled.

      The implementation materialises all elements into an array before shuffling, making this unsuitable for infinite sequences.

      const numbers = from([1, 2, 3, 4, 5]);
      const shuffled = numbers.shuffle().toArray();
      console.log(shuffled); // e.g., [3, 1, 5, 2, 4]
    • Returns the only element that satisfies the provided type guard predicate.

      Type Parameters

      • TFiltered

        extends TElement Narrowed element type produced when predicate returns true.

      Parameters

      Returns TFiltered

      The single element that satisfies predicate.

      Thrown when the sequence is empty.

      Thrown when no element satisfies predicate.

      Thrown when more than one element satisfies predicate.

      The source is fully enumerated to ensure exactly one matching element exists.

      const numbers = from([5]);
      const singleElement = numbers.single();
      console.log(singleElement); // 5

      const numbers2 = from([1, 2, 3, 4, 5]);
      const singleEven = numbers2.single(x => x > 4);
      console.log(singleEven); // 5
    • Returns the only element in the sequence or the only element that satisfies an optional predicate.

      Parameters

      • Optionalpredicate: Predicate<TElement>

        Optional predicate evaluated for each element. When provided, the result must be the unique element for which it returns true.

      Returns TElement

      The single element in the sequence or the single element that satisfies predicate.

      Thrown when the sequence is empty.

      Thrown when more than one element exists and predicate is omitted.

      Thrown when predicate is provided and no element satisfies it.

      Thrown when predicate is provided and more than one element satisfies it.

      The source is fully enumerated to validate uniqueness.

    • Returns the only element that satisfies the provided type guard predicate, or null when no such element exists.

      Type Parameters

      • TFiltered

        extends TElement Narrowed element type produced when predicate returns true.

      Parameters

      Returns TFiltered | null

      The single matching element, or null when no element satisfies predicate.

      Thrown when more than one element satisfies predicate.

      The source is fully enumerated to confirm uniqueness of the matching element.

      const numbers = from([5]);
      const singleElement = numbers.singleOrDefault();
      console.log(singleElement); // 5

      const numbers2 = from([1, 2, 3, 4, 5]);
      const singleEven = numbers2.singleOrDefault(x => x > 4);
      console.log(singleEven); // 5

      const empty = from<number>([]);
      const singleOfEmpty = empty.singleOrDefault();
      console.log(singleOfEmpty); // null

      const noMatch = from([1, 2, 3]);
      const singleNoMatch = noMatch.singleOrDefault(x => x > 4);
      console.log(singleNoMatch); // null
    • Returns the only element in the sequence or the only element that satisfies an optional predicate, or null when no such element exists.

      Parameters

      • Optionalpredicate: Predicate<TElement>

        Optional predicate evaluated for each element. When provided, the result must be the unique element for which it returns true.

      Returns TElement | null

      The single element or matching element, or null when no element satisfies the conditions.

      Thrown when more than one element exists and predicate is omitted.

      Thrown when predicate is provided and more than one element satisfies it.

      The source is fully enumerated. Unlike single, this method returns null instead of throwing when no matching element is found.

    • Skips a specified number of elements before yielding the remainder of the sequence.

      Parameters

      • count: number

        Number of elements to bypass. Values less than or equal to zero result in no elements being skipped.

      Returns IEnumerable<TElement>

      A deferred sequence containing the elements that remain after skipping count items.

      Enumeration is deferred. Only the skipped prefix is traversed without yielding.

      const numbers = from([1, 2, 3, 4, 5]);
      const skipped = numbers.skip(2).toArray();
      console.log(skipped); // [3, 4, 5]
    • Omits a specified number of elements from the end of the sequence.

      Parameters

      • count: number

        Number of trailing elements to exclude. Values less than or equal to zero leave the sequence unchanged.

      Returns IEnumerable<TElement>

      A deferred sequence excluding the last count elements.

      The implementation buffers up to count elements to determine which items to drop, which can increase memory usage for large values.

      const numbers = from([1, 2, 3, 4, 5]);
      const skipped = numbers.skipLast(2).toArray();
      console.log(skipped); // [1, 2, 3]
    • Calculates the standard deviation of the numeric values produced by the sequence.

      Parameters

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element. Defaults to the element itself.

      • Optionalsample: boolean

        When true, computes the sample standard deviation; when false, computes the population standard deviation. Defaults to true.

      Returns number

      The calculated standard deviation, or NaN when there are insufficient values to compute it.

      Re-throws any error thrown while iterating the sequence or executing selector.

      This method delegates to variance; when the variance is NaN, that value is returned unchanged. The sequence is enumerated exactly once using a numerically stable single-pass algorithm.

      const populationStdDev = from([1, 2, 3, 4, 5]).standardDeviation(x => x, false);
      console.log(populationStdDev); // Math.sqrt(2)
    • Returns every n-th element of the sequence, starting with the first.

      Parameters

      • step: number

        Positive interval indicating how many elements to skip between yielded items.

      Returns IEnumerable<TElement>

      A deferred sequence containing elements whose zero-based index is divisible by step.

      Thrown when step is less than 1.

      The source is enumerated exactly once; elements that are not yielded are still visited.

      const numbers = from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
      const stepped = numbers.step(3).toArray();
      console.log(stepped); // [1, 4, 7]
    • Computes the sum of the numeric values produced for each element.

      Parameters

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value. Defaults to interpreting the element itself as a number.

      Returns number

      The sum of the projected values.

      Thrown when the sequence is empty.

      The source is enumerated exactly once. Supply selector when elements are not already numeric.

      const numbers = from([1, 2, 3, 4, 5]);
      const total = numbers.sum();
      console.log(total); // 15

      const people = from([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      ]);
      const totalAge = people.sum(p => p.age);
      console.log(totalAge); // 55
    • Returns up to the specified number of leading elements.

      Parameters

      • count: number

        Number of elements to emit; values less than or equal to zero produce an empty sequence.

      Returns IEnumerable<TElement>

      A deferred sequence containing at most count elements from the start of the source.

      Enumeration stops once count elements have been yielded or the source sequence ends.

      const numbers = from([1, 2, 3, 4, 5]);
      const firstTwo = numbers.take(2).toArray();
      console.log(firstTwo); // [1, 2]

      const emptyTake = numbers.take(0).toArray();
      console.log(emptyTake); // []
    • Returns up to the specified number of trailing elements.

      Parameters

      • count: number

        Number of elements to keep from the end; values less than or equal to zero produce an empty sequence.

      Returns IEnumerable<TElement>

      A deferred sequence containing at most count elements from the end of the source.

      The implementation buffers up to count elements to determine the tail, so memory usage grows with count. The source must be finite.

      const numbers = from([1, 2, 3, 4, 5]);
      const lastTwo = numbers.takeLast(2).toArray();
      console.log(lastTwo); // [4, 5]

      const emptyTakeLast = numbers.takeLast(0).toArray();
      console.log(emptyTakeLast); // []
    • Invokes the specified action for each element while yielding the original elements unchanged.

      Parameters

      Returns IEnumerable<TElement>

      The original sequence, enabling fluent chaining.

      The action executes lazily as the sequence is iterated, making it suitable for logging or instrumentation.

      const numbers = from([1, 2, 3]);
      const tapped = numbers
      .tap(x => console.log(`Processing: ${x}`))
      .select(x => x * 2)
      .toArray();
      console.log(tapped); // [2, 4, 6]
      // Expected console output:
      // Processing: 1
      // Processing: 2
      // Processing: 3
    • Materialises the sequence into an array.

      Returns TElement[]

      An array containing all elements from the source sequence in iteration order.

      The entire sequence is enumerated immediately. Subsequent changes to the source are not reflected in the returned array.

      const numbers = from([1, 2, 3]);
      const array = numbers.toArray();
      console.log(array); // [1, 2, 3]
    • Materialises the sequence into an enumerable set containing the distinct elements.

      Returns EnumerableSet<TElement>

      A set populated with the distinct elements from the source.

      The entire sequence is enumerated immediately and duplicate elements are collapsed using the set's equality semantics.

      const numbers = from([1, 2, 2, 3, 1]);
      const set = numbers.toEnumerableSet();
      console.log(set.toArray()); // [1, 2, 3]
    • Materialises the sequence into an immutable set containing the distinct elements.

      Returns ImmutableSet<TElement>

      An immutable set built from the distinct elements of the source.

      The entire sequence is enumerated immediately and duplicate elements are collapsed using the set's equality semantics.

      const numbers = from([1, 2, 2, 3, 1]);
      const immutableSet = numbers.toImmutableSet();
      console.log(immutableSet.toArray()); // [1, 2, 3]
    • Materialises the sequence into a lookup keyed by the provided selector.

      Type Parameters

      Parameters

      Returns ILookup<TKey, TValue>

      A lookup grouping the projected values by key.

      The entire sequence is enumerated immediately. Elements within each group preserve their original order and the groups are cached for repeated enumeration.

      const products = from([
      { name: 'Apple', category: 'Fruit' },
      { name: 'Banana', category: 'Fruit' },
      { name: 'Carrot', category: 'Vegetable' },
      ]);
      const lookup = products.toLookup(p => p.category, p => p.name);
      console.log(lookup.get('Fruit').toArray()); // ['Apple', 'Banana']
      console.log(lookup.get('Vegetable').toArray()); // ['Carrot']
    • Materialises the sequence into a plain object keyed by the provided selector.

      Type Parameters

      • TKey extends PropertyKey

        extends string | number | symbol Property key type returned by keySelector.

      • TValue

        Type of value returned by valueSelector.

      Parameters

      Returns Record<TKey, TValue>

      An object populated with the projected key/value pairs.

      The entire sequence is enumerated immediately. When keySelector produces duplicate keys, later values overwrite earlier ones.

      const people = from([
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' },
      ]);
      const obj = people.toObject(p => p.id, p => p.name);
      console.log(obj[1]); // 'Alice'
      console.log(obj[2]); // 'Bob'
    • Materialises the sequence into a native Set.

      Returns Set<TElement>

      A set containing the distinct elements from the source.

      The entire sequence is enumerated immediately and duplicate elements are collapsed using JavaScript's SameValueZero semantics.

      const numbers = from([1, 2, 2, 3, 1]);
      const set = numbers.toSet();
      console.log(Array.from(set)); // [1, 2, 3]
    • Returns a string representation of this collection.

      Returns string

      A string representation of this collection.

    • Returns a string representation of this collection.

      Parameters

      • Optionalseparator: string

        The separator that will be used to separate the elements of this collection.

      Returns string

      A string representation of this collection.

    • Returns a string representation of this collection.

      Parameters

      • Optionalseparator: string

        The separator that will be used to separate the elements of this collection.

      • Optionalselector: Selector<TElement, string>

        The selector that will be used to select the property that will be used to generate the string representation of this collection.

      Returns string

      A string representation of this collection.

    • Creates a set-style union between this sequence and iterable using an equality comparator.

      Parameters

      • iterable: Iterable<TElement>

        Additional sequence whose elements are appended after the source when forming the union.

      • Optionalcomparator: EqualityComparator<TElement, TElement>

        Optional equality comparator that determines whether two elements are considered the same. Defaults to the library's standard equality comparator.

      Returns IEnumerable<TElement>

      A deferred sequence containing the distinct elements from this sequence followed by elements from iterable that are not already present according to comparator.

      Re-throws any error thrown while iterating either sequence or executing comparator.

      Elements from the original sequence always appear before contributions from iterable. The method caches only the comparison keys needed to detect duplicates and enumerates each input at most once.

      const numbers1 = from([1, 2, 3, 4, 5]);
      const numbers2 = [3, 5, 6, 7];
      const unioned = numbers1.union(numbers2).toArray();
      console.log(unioned); // [1, 2, 3, 4, 5, 6, 7]
    • Creates a set-style union between this sequence and iterable by comparing keys projected from each element.

      Type Parameters

      Parameters

      • iterable: Iterable<TElement>

        Additional sequence whose elements are appended after the source when forming the union.

      • keySelector: Selector<TElement, TKey>

        Projection that produces a comparison key for each element.

      • Optionalcomparator: EqualityComparator<TKey, TKey>

        Optional equality comparator that determines whether two keys are considered the same. Defaults to the library's standard equality comparator.

      Returns IEnumerable<TElement>

      A deferred sequence containing the distinct elements from this sequence followed by elements from iterable whose keys were not previously observed.

      Re-throws any error thrown while iterating either sequence or executing keySelector or comparator.

      Keys are buffered to ensure uniqueness while the elements themselves remain lazily produced. Provide comparator when keys require structural equality semantics.

      const products1 = from([
      { name: 'Apple', category: 'Fruit' },
      { name: 'Banana', category: 'Fruit' },
      ]);
      const products2 = [
      { name: 'Carrot', category: 'Vegetable' },
      { name: 'Apple', category: 'Fruit' },
      ];

      const unioned = products1.unionBy(products2, p => p.category).toArray();
      console.log(unioned);
      // [
      // { name: 'Apple', category: 'Fruit' },
      // { name: 'Banana', category: 'Fruit' },
      // { name: 'Carrot', category: 'Vegetable' }
      // ]
    • Calculates the variance of the numeric values produced by the sequence.

      Parameters

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element. Defaults to the element itself.

      • Optionalsample: boolean

        When true, computes the sample variance dividing by n - 1; when false, computes the population variance dividing by n. Defaults to true.

      Returns number

      The calculated variance, or NaN when the sequence is empty—or for sample variance when it contains a single element.

      Re-throws any error thrown while iterating the sequence or executing selector.

      A numerically stable single-pass algorithm (Welford's method) is used, so the source is enumerated exactly once regardless of size.

      const populationVariance = from([1, 2, 3, 4, 5]).variance(x => x, false);
      console.log(populationVariance); // 2
    • Produces a sequence of sliding windows of fixed size over the source sequence.

      Parameters

      • size: number

        Length of each window; must be at least 1.

      Returns IEnumerable<IEnumerable<TElement>>

      A deferred sequence where each element exposes one contiguous window from the source.

      Thrown when size is less than 1.

      Re-throws any error thrown while iterating the source sequence.

      Windows overlap and are yielded only after enough source elements are observed to fill size. Trailing partial windows are omitted.

      const numbers = from([1, 2, 3, 4, 5]);
      const windows = numbers.windows(3);
      console.log(windows.select(w => w.toArray()).toArray()); // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
    • Combines this sequence with iterable and yields tuples of aligned elements.

      Type Parameters

      • TSecond

        Type of elements produced by iterable.

      Parameters

      • iterable: Iterable<TSecond>

        The secondary sequence whose elements are paired with the source elements.

      Returns IEnumerable<[TElement, TSecond]>

      A deferred sequence of [source, other] tuples truncated to the length of the shorter input.

      Re-throws any error thrown while iterating either sequence.

      Enumeration is lazy; pairs are produced on demand and iteration stops when either sequence completes. Use the overload that accepts a zipper when you need to project custom results.

      const numbers = from([1, 2, 3]);
      const letters = ['a', 'b', 'c'];
      const zipped = numbers.zip(letters).toArray();
      console.log(zipped); // [[1, 'a'], [2, 'b'], [3, 'c']]

      const zippedWithSelector = numbers.zip(letters, (num, letter) => `${num}-${letter}`).toArray();
      console.log(zippedWithSelector); // ['1-a', '2-b', '3-c']
    • Combines this sequence with iterable and projects each aligned pair using zipper.

      Type Parameters

      • TSecond

        Type of elements produced by iterable.

      • TResult

        Result type produced by zipper.

      Parameters

      • iterable: Iterable<TSecond>

        The secondary sequence whose elements are paired with the source elements.

      • zipper: Zipper<TElement, TSecond, TResult>

        Projection invoked with each [source, other] pair to produce the resulting element.

      Returns IEnumerable<TResult>

      A deferred sequence of projected results truncated to the length of the shorter input.

      Re-throws any error thrown while iterating either sequence or executing zipper.

      Enumeration is lazy; the zipper function executes on demand for each pair and iteration stops when either sequence completes.

    • Zips this sequence with the iterables supplied in iterables, producing aligned tuples.

      Type Parameters

      • TIterable extends readonly Iterable<unknown, any, any>[]

        Extends readonly Iterable<unknown>[]; the element type of each iterable contributes to the resulting tuple.

      Parameters

      • ...iterables: [...TIterable[]]

        Additional sequences to zip with the source.

      Returns IEnumerable<[TElement, ...UnpackIterableTuple<TIterable>[]]>

      A deferred sequence of tuples truncated to the length of the shortest input.

      Re-throws any error raised while iterating the source or any of the supplied iterables.

      Iteration stops as soon as any participating iterable is exhausted. Tuple element types are inferred from the supplied iterables, preserving strong typing across the zipped result.

      const zipped = from([1, 2, 3]).zipMany(['A', 'B', 'C'], [true, false]).toArray();
      console.log(zipped); // [[1, 'A', true], [2, 'B', false]]
    • Zips this sequence with the iterables supplied in iterablesAndZipper and projects each tuple with ZipManyZipper zipper.

      Type Parameters

      • TIterable extends readonly Iterable<unknown, any, any>[]

        Extends readonly Iterable<unknown>[]; the element type of each iterable contributes to the zipper input tuple.

      • TResult

        Result type produced by ZipManyZipper zipper.

      Parameters

      • ...iterablesAndZipper: [
            ...TIterable[],
            ZipManyZipper<[TElement, ...UnpackIterableTuple<TIterable>[]], TResult>,
        ]

        The trailing argument may be a zipper invoked with each tuple to produce a projected result; preceding arguments are the iterables to zip with.

      Returns IEnumerable<TResult>

      A deferred sequence of projected results truncated to the length of the shortest input.

      Re-throws any error raised while iterating the source, the supplied iterables, or executing the zipper.

      The zipper receives a readonly tuple [source, ...others] for each aligned set. Iteration stops as soon as any participating iterable is exhausted.

      const labels = from([1, 2, 3]).zipMany(
      ['A', 'B', 'C'],
      [true, true, false],
      ([num, letter, flag]) => `${num}${letter}-${flag ? "yes" : "no"}`
      ).toArray();
      console.log(labels); // ["1A-yes", "2B-yes", "3C-no"]