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

    Function lastOrDefault

    • Returns the last 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 last element of the sequence is returned. When a type guard is supplied, the returned value is narrowed to TFiltered.

      Returns TFiltered | 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 function never throws for missing elements; it communicates absence through the null return value.

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

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

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

      const noEvens = [1, 3, 5];
      const lastEven2 = lastOrDefault(noEvens, x => x % 2 === 0);
      console.log(lastEven2); // null
    • Returns the last 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 final element of the sequence is returned.

      Returns TElement | null

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

      Unlike last, this overload communicates absence through null instead of throwing.