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

    Function firstOrDefault

    • Returns the first element in the sequence or null when the sequence is empty or no element satisfies the predicate.

      Type Parameters

      • TElement

        Type of elements within the source iterable.

      • TFiltered

        Subtype confirmed when a type guard predicate is supplied.

      Parameters

      • source: Iterable<TElement>

        The source iterable.

      • predicate: TypePredicate<TElement, TFiltered>

        Predicate evaluated against each element; when omitted, the first element is returned. When a type guard is supplied, the returned value is narrowed to TFiltered.

      Returns TFiltered | null

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

      This function never throws for missing elements; it communicates absence through the null return value.

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

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

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

      const noEvens = [1, 3, 5];
      const firstEven2 = firstOrDefault(noEvens, x => x % 2 === 0);
      console.log(firstEven2); // null
    • Returns the first element in the sequence that satisfies an optional predicate, or null when none does.

      Type Parameters

      • TElement

        Type of elements within the source iterable.

      Parameters

      • source: Iterable<TElement>

        The source iterable.

      • Optionalpredicate: Predicate<TElement>

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

      Returns TElement | null

      The first element that satisfies predicate, or null when the sequence is empty or no element matches.

      This overload never throws for missing elements; use first when absence should raise an exception.