🧩 Creates a slice of array with elements taken from the beginning or end while the predicate returns true.

Syntax

TypeScript
import { takeWhile } from '@opentf/std';

takeWhile<T>(arr: T[] = [], predicate: (val: T, index: number, arr: T[]) => boolean, right?: boolean): T[]

Parameters

  • arr: The source array.

  • predicate: The function invoked per element. Receives (value, index, array).

  • right: If true, takes from the end while preserving the original callback indexes and array.

Returns

A new array with taken elements until the predicate returns false.

Examples

TypeScript
takeWhile([1, 2, 3, 4, 5], (n) => n < 4) //=> [1, 2, 3]

takeWhile([1, 2, 3], (n) => n > 3) //=> []

takeWhile([1, 2, 3], (n) => n < 10) //=> [1, 2, 3]

takeWhile([true, true, false, true], Boolean) //=> [true, true]

takeWhile([1, 2, 3, 4, 5], (n) => n > 3, true) //=> [4, 5]
Last updated on
Edit this page