-
Notifications
You must be signed in to change notification settings - Fork 343
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add test case of take into combat
- Loading branch information
Showing
3 changed files
with
54 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |