🍴 Takes a specified number of elements from the start of an array.
Info
It is loosely based on the Iterator.prototype.take() method.
Syntax
TypeScript
import { take } from '@opentf/std'; take<T>( arr: T[], limit: number | null = 1, cb?: (val: T) => boolean, right?: boolean ): T[]
Parameters
arr: The source array.limit: The number of elements to take. Ifnull, all elements are taken.cb: An optional predicate function. If provided, only elements that returntrueare taken, up to the limit.right: Iftrue, takes from the end of the array instead of the start. Default:false.
Returns
A new array containing the taken elements.
Examples
TypeScript
take([1, 2, 3], -1) // Throws RangeError for negative limit take([1, 2, 3], 0) //=> [] take([1, 2, 3]) //=> [1] take([1, 2, 3], 1) //=> [1] take([1, 2, 3], 2) //=> [1, 2] take([1, 2, 3, 4, 5], 5) //=> [1, 2, 3, 4, 5] take([1, 2, 3, 4, 5], 6) //=> [1, 2, 3, 4, 5] take([1, 2, 3, 4, 5], null) //=> [1, 2, 3, 4, 5] take([1, 2, 3, 4, 5], 2, (val) => val % 2 === 0) //=> [2, 4] take([1, 2, 3, 4, 5], 3, (val) => val % 2 !== 0) //=> [1, 3, 5] take([1, 2, 3, 4, 5], 2, undefined, true) //=> [4, 5] const users = [ { name: 'x', active: false }, { name: 'y', active: true }, { name: 'z', active: false }, ]; take(users, null, (val) => val.active) //=> [ // { name: 'y', active: true }, // ]