All files / collections / unstable_take_last_while.ts

100.00% Branches 9/9
100.00% Lines 20/20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x2
x2
 
x16
x25
x25
x41
x41
x25
x25
x34
x29
x49
x65
x49
x53
x53
x49
x34
x16















































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Returns all elements in the given iterable after the last element that does not
 * match the given predicate.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @typeParam T The type of the iterable elements.
 *
 * @param iterable The iterable to take elements from.
 * @param predicate The predicate function to determine if an element should be
 * included.
 *
 * @returns An array containing all elements after the last element that does
 * not match the predicate.
 *
 * @example Basic usage
 * ```ts
 * import { takeLastWhile } from "@std/collections/unstable-take-last-while";
 * import { assertEquals } from "@std/assert";
 *
 * const numbers = [1, 2, 3, 4, 5, 6];
 * const result = takeLastWhile(numbers, (number) => number > 4);
 * assertEquals(result, [5, 6]);
 * ```
 */
export function takeLastWhile<T>(
  iterable: Iterable<T>,
  predicate: (el: T) => boolean,
): T[] {
  if (Array.isArray(iterable)) {
    let offset = iterable.length;
    while (0 < offset && predicate(iterable[offset - 1] as T)) {
      offset--;
    }
    return iterable.slice(offset);
  }
  const result: T[] = [];
  for (const el of iterable) {
    if (predicate(el)) {
      result.push(el);
    } else {
      result.length = 0;
    }
  }
  return result;
}