Skip to content

Commit

Permalink
feat: add test case of take into combat
Browse files Browse the repository at this point in the history
  • Loading branch information
choi2021 committed Jul 18, 2024
1 parent bc7ea93 commit 1d70fb1
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,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) | 📝 |
Expand Down
22 changes: 22 additions & 0 deletions src/compat/array/take.spec.ts
Original file line number Diff line number Diff line change
@@ -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 changes: 31 additions & 0 deletions src/compat/array/take.ts
Original file line number Diff line number Diff line change
@@ -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);
}

0 comments on commit 1d70fb1

Please sign in to comment.