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

    Function takeWhile

    • Returns consecutive leading elements while a type guard predicate continues to succeed, narrowing the element type.

      Type Parameters

      • TElement

        Type of elements within source.

      • TFiltered

        extends TElement Narrowed element type produced by predicate.

      Parameters

      Returns IEnumerable<TFiltered>

      A deferred sequence containing the contiguous prefix that satisfies predicate.

      Elements after the first failing element are not inspected. Use this overload when you need the result to reflect the guarded type.

      const mixed: (number | string)[] = [1, 2, 'three', 4, 5];
      const numbers = takeWhile(mixed, (x): x is number => typeof x === 'number').toArray();
      console.log(numbers); // [1, 2]
    • Returns consecutive leading elements while a predicate returns true.

      Type Parameters

      • TElement

        Type of elements within source.

      Parameters

      • source: Iterable<TElement>

        The source iterable.

      • predicate: IndexedPredicate<TElement>

        Predicate invoked for each element and its zero-based index; iteration stops immediately when it returns false.

      Returns IEnumerable<TElement>

      A deferred sequence containing the contiguous prefix that satisfies predicate.

      Elements after the first failing element are not inspected.

      const numbers = [1, 2, 3, 4, 5, 1, 2];
      const taken = takeWhile(numbers, x => x < 4).toArray();
      console.log(taken); // [1, 2, 3]

      const takenWithIndex = takeWhile(numbers, (x, i) => i < 3).toArray();
      console.log(takenWithIndex); // [1, 2, 3]