take
Returns a new array containing the first n elements of the array.
If no additional argument is provided, returns a new array containing only the first element.
If the count to take is greater than the array length, returns the entire array.
If the count to take is negative, returns an empty array.
Code
Benchmark
hz: Operations per secondmean: Average response time (ms)
| Name | hz | mean | Performance |
|---|---|---|---|
| modern-kit/take | 6,771,043.43 | 0.0001 | fastest |
| lodash/take | 2,601,105.35 | 0.0004 | slowest |
- modern-kit/take
2.60xfaster than lodash/take
Interface
typescript
function take<T>(arr: T[] | readonly T[], count: number = 1): T[]
Usage
typescript
import { take } from '@modern-kit/utils';
const arr = [1, 2, 3, 4, 5];
console.log(take(arr)); // [1]
console.log(take(arr, 0)); // []
console.log(take(arr, 2)); // [1, 2]
console.log(take(arr, 7)); // [1, 2, 3, 4, 5]