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

    Class ImmutableSortedDictionary<TKey, TValue>

    Type Parameters

    • TKey
    • TValue

    Hierarchy

    • AbstractImmutableDictionary<TKey, TValue>
      • ImmutableSortedDictionary
    Index

    Properties

    valueComparer: EqualityComparator<TValue>

    Accessors

    Methods

    • Determines whether every element in the sequence satisfies the supplied predicate.

      Parameters

      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<KeyValuePair<TKey, TValue>>

        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
    • Returns an object representation of this dictionary.

      toObject is a more versatile version of this method, as it allows you to select the key and value properties that will be used to generate the object representation.

      Type Parameters

      • TObjectKey extends PropertyKey

      Returns Record<TObjectKey, TValue>

      An object representation of this dictionary.

    • 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<KeyValuePair<TKey, TValue>>

        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<KeyValuePair<TKey, TValue>>

        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<KeyValuePair<TKey, TValue>, 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<[KeyValuePair<TKey, TValue>, 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<KeyValuePair<TKey, TValue>>>

      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<KeyValuePair<TKey, TValue>>>

      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<KeyValuePair<TKey, TValue>>

      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]
    • 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<KeyValuePair<TKey, TValue>, 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

      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<KeyValuePair<TKey, TValue>>

        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
    • 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<KeyValuePair<TKey, TValue>, 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<KeyValuePair<TKey, TValue>, number>

        Projection that produces the first numeric series for each element.

      • rightSelector: Selector<KeyValuePair<TKey, TValue>, 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<KeyValuePair<TKey, TValue>>

      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: KeyValuePair<TKey, TValue> | null

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

      Returns IEnumerable<KeyValuePair<TKey, TValue> | 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
    • Removes consecutive duplicate elements by comparing keys projected from each element.

      Type Parameters

      • TDistinctKey

      Parameters

      Returns IEnumerable<KeyValuePair<TKey, TValue>>

      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 KeyValuePair<TKey, TValue>

      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 KeyValuePair<TKey, TValue> | 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<KeyValuePair<TKey, TValue>>

        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 first element that satisfies the provided type guard, or null when no such element exists.

      Type Parameters

      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

      Returns KeyValuePair<TKey, TValue> | null

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

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

    • Executes the provided callback for every element in the sequence.

      Parameters

      Returns void

      Enumeration starts immediately. Avoid mutating the underlying collection while iterating.

      const numbers = from([1, 2, 3]);
      numbers.forEach((x, i) => console.log(`Index ${i}: ${x}`));
      // Index 0: 1
      // Index 1: 2
      // Index 2: 3
    • Enumerates the sequence while exposing the zero-based index alongside each element.

      Returns IEnumerable<[number, KeyValuePair<TKey, TValue>]>

      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<KeyValuePair<TKey, TValue> | 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 last element that satisfies the provided type guard, or null when no such element exists.

      Type Parameters

      Parameters

      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<KeyValuePair<TKey, TValue>>

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

      Returns KeyValuePair<TKey, TValue> | 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.

      • TGroupKey
      • TResult

        Type of element returned by resultSelector.

      Parameters

      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<KeyValuePair<TKey, TValue>, 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
    • Calculates the median of the numeric values produced by the sequence.

      Parameters

      • Optionalselector: Selector<KeyValuePair<TKey, TValue>, 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<KeyValuePair<TKey, TValue>, 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 that appears most frequently in the sequence.

      Type Parameters

      • TModeKey

      Parameters

      Returns KeyValuePair<TKey, TValue>

      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

      • TModeKey

      Parameters

      Returns KeyValuePair<TKey, TValue> | 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

      • TModeKey

      Parameters

      Returns IEnumerable<KeyValuePair<TKey, TValue>>

      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<KeyValuePair<TKey, TValue>>

        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]
    • 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<KeyValuePair<TKey, TValue>, 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<KeyValuePair<TKey, TValue>>>

      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]
    • Computes the multiplicative aggregate of the values produced for each element.

      Parameters

      • Optionalselector: Selector<KeyValuePair<TKey, TValue>, 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<KeyValuePair<TKey, TValue>>

      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.

      • TGroupKey
      • TResult

        Type of element returned by resultSelector.

      Parameters

      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<KeyValuePair<TKey, TValue>>

      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]
    • 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

      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<KeyValuePair<TKey, TValue>>

      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, or null when no such element exists.

      Type Parameters

      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<KeyValuePair<TKey, TValue>>

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

      Returns KeyValuePair<TKey, TValue> | 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<KeyValuePair<TKey, TValue>>

      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<KeyValuePair<TKey, TValue>>

      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<KeyValuePair<TKey, TValue>, 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

      • stepNumber: number

      Returns IEnumerable<KeyValuePair<TKey, TValue>>

      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<KeyValuePair<TKey, TValue>, 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<KeyValuePair<TKey, TValue>>

      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<KeyValuePair<TKey, TValue>>

      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); // []
    • Materialises the sequence into an array.

      Returns KeyValuePair<TKey, TValue>[]

      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<KeyValuePair<TKey, TValue>>

      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<KeyValuePair<TKey, TValue>>

      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 native Set.

      Returns Set<KeyValuePair<TKey, TValue>>

      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]
    • Creates a set-style union between this sequence and iterable by comparing keys projected from each element.

      Type Parameters

      • TUnionKey

      Parameters

      Returns IEnumerable<KeyValuePair<TKey, TValue>>

      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<KeyValuePair<TKey, TValue>, 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<KeyValuePair<TKey, TValue>>>

      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]]
    • 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<[KeyValuePair<TKey, TValue>, ...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<
                [KeyValuePair<TKey, TValue>, ...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"]