test: Add test cases for take (#252)

Co-authored-by: Sojin Park <raon0211@toss.im>
This commit is contained in:
Youngjun Choi 2024-07-20 11:04:28 +09:00 committed by GitHub
parent 0b71ce9b56
commit 3f7136734b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 54 additions and 1 deletions

View File

@ -94,7 +94,7 @@ Even if a feature is marked "in review," it might already be under review to ens
| [sortedUniq](https://lodash.com/docs/4.17.15#sortedUniq) | No support |
| [sortedUniqBy](https://lodash.com/docs/4.17.15#sortedUniqBy) | No support |
| [tail](https://lodash.com/docs/4.17.15#tail) | ✅ |
| [take](https://lodash.com/docs/4.17.15#take) | 📝 |
| [take](https://lodash.com/docs/4.17.15#take) | |
| [takeRight](https://lodash.com/docs/4.17.15#takeRight) | 📝 |
| [takeRightWhile](https://lodash.com/docs/4.17.15#takeRightWhile) | 📝 |
| [takeWhile](https://lodash.com/docs/4.17.15#takeWhile) | 📝 |

View File

@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest';
import { take } from './take.ts';
describe('take', () => {
const array = [1, 2, 3];
it('should take the first two elements', () => {
expect(take(array, 2)).toEqual([1, 2]);
});
it('should return an empty array when `n` < `1`', () => {
[0, -1, -Infinity].forEach(n => {
expect(take(array, n)).toEqual([]);
});
});
it('should return all elements when `n` >= `length`', () => {
[3, 4, 2 ** 32, Infinity].forEach(n => {
expect(take(array, n)).toEqual(array);
});
});
});

31
src/compat/array/take.ts Normal file
View File

@ -0,0 +1,31 @@
import { take as takeToolkit } from '../../array/take.ts';
/**
* Returns a new array containing the first `count` elements from the input array `arr`.
* If `count` is greater than the length of `arr`, the entire array is returned.
*
* @template T - Type of elements in the input array.
*
* @param {T[]} arr - The array to take elements from.
* @param {number} count - The number of elements to take.
* @returns {T[]} A new array containing the first `count` elements from `arr`.
*
* @example
* // Returns [1, 2, 3]
* take([1, 2, 3, 4, 5], 3);
*
* @example
* // Returns ['a', 'b']
* take(['a', 'b', 'c'], 2);
*
* @example
* // Returns [1, 2, 3]
* take([1, 2, 3], 5);
*/
export function take<T>(arr: readonly T[], count: number): T[] {
if (count < 1) {
return [];
}
return takeToolkit(arr, count);
}