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

    Function single

    • Returns the only element that satisfies the provided type guard predicate.

      Type Parameters

      • TElement

        Type of elements within the source iterable.

      • TFiltered

        extends TElement Narrowed element type produced when predicate returns true.

      Parameters

      Returns TFiltered

      The single element that satisfies predicate.

      Thrown when source is empty.

      Thrown when no element satisfies predicate.

      Thrown when more than one element satisfies predicate.

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

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

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

      Type Parameters

      • TElement

        Type of elements within the source iterable.

      Parameters

      • source: Iterable<TElement>

        The source iterable.

      • 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 source or the single element that satisfies predicate.

      Thrown when source 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.

      source is fully enumerated to validate uniqueness.