feat(sortBy): Refactor sortBy and improve docs
Some checks are pending
CI / codecov (push) Waiting to run
Release / release (push) Waiting to run

This commit is contained in:
Sojin Park 2024-08-15 11:33:40 +09:00
parent 21a0ceabc5
commit d4037c755c
6 changed files with 83 additions and 48 deletions

View File

@ -83,6 +83,7 @@ function sidebar(): DefaultTheme.Sidebar {
{ text: 'sampleSize', link: '/zh_hans/reference/array/sampleSize' }, { text: 'sampleSize', link: '/zh_hans/reference/array/sampleSize' },
{ text: 'shuffle', link: '/zh_hans/reference/array/shuffle' }, { text: 'shuffle', link: '/zh_hans/reference/array/shuffle' },
{ text: 'size (兼容性)', link: '/zh_hans/reference/compat/array/size' }, { text: 'size (兼容性)', link: '/zh_hans/reference/compat/array/size' },
{ text: 'sortBy', link: '/zh_hans/reference/array/sortBy' },
{ text: 'take', link: '/zh_hans/reference/array/take' }, { text: 'take', link: '/zh_hans/reference/array/take' },
{ text: 'takeWhile', link: '/zh_hans/reference/array/takeWhile' }, { text: 'takeWhile', link: '/zh_hans/reference/array/takeWhile' },
{ text: 'takeRight', link: '/zh_hans/reference/array/takeRight' }, { text: 'takeRight', link: '/zh_hans/reference/array/takeRight' },

View File

@ -1,29 +1,26 @@
# sortBy # sortBy
주어진 `iteratees` (또는 키)에 따라 객체 배열을 오름차순으로 정렬해요. 주어진 조건 `criteria`에 따라 객체로 이루어진 배열을 정렬해요.
이 함수는 객체 배열, 정렬할 기준이 되는 iteratee (또는 키)의 배열을 받아요. - 조건이 프로퍼티 이름이면, 해당하는 프로퍼티 값에 따라 정렬해요.
오름차순으로 정렬된 객체 배열을 반환해요. - 조건이 함수이면, 함수가 반환하는 값에 따라 정렬해요.
`iteratees`가 객체의 키일 경우엔 해당 키에 해당하는 값을 기준으로 정렬해요.
`iteratees``iteratee` 함수일 경우엔 해당 함수의 반환값을 기준으로 정렬해요.
키의 값이 동일한 경우 다음 키를 기준으로 정렬 순서를 결정해요.
> `iteratee` 함수는 객체를 매개변수로 받고 값을 반환하는 함수에요. 배열은 오름차순으로 정렬돼요. 조건에 따라 두 요소의 값이 같으면, 다음 조건으로 정렬해요.
## 인터페이스 ## 인터페이스
```typescript ```typescript
function sortBy<T extends object>(collection: T[], iteratees: Array<Iteratee<T> | keyof T>): T[]; function sortBy<T extends object>(arr: T[], criteria: Array<((item: T) => unknown) | keyof T>): T[];
``` ```
### 파라미터 ### 파라미터
- `collection` (`T[]`): 정렬할 객체 배열. - `arr` (`T[]`): 정렬할 객체 배열.
- `iteratees` (`Array<Iteratee<T> | keyof T>`): 정렬할 기준이 되는 iteratee 또는 키의 배열. - `criteria` (`Array<((item: T) => unknown) | keyof T>`): 정렬할 기준. 객체의 프로퍼티 이름이나 함수를 쓸 수 있어요.
### 반환 값 ### 반환 값
(`T[]`) 정렬된 배열. (`T[]`) 오름차순으로 정렬된 배열.
## 예시 ## 예시

View File

@ -1,31 +1,28 @@
# sortBy # sortBy
Sorts an array of objects based on the given `iteratees` (or keys) in ascending order. Sorts an array of objects based on the given `criteria`.
This function takes an array of objects, an array of iteratees (or keys) to sort by. - If you provide keys, it sorts the objects by the values of those keys.
It returns the ascendingly sorted array of objects. - If you provide functions, it sorts based on the values returned by those functions.
If `iteratees` are keys of the object, it sorts based on the values of the keys.
If `iteratees` are iteratee functions, it sorts based on the return values of the functions.
If values for a key are equal, it moves to the next key to determine the order.
> An `iteratee` is a function that takes an object and returns a value. The function returns the array of objects sorted in ascending order. If two objects have the same value for the current criterion, it uses the next criterion to determine their order.
## Signature ## Signature
```typescript ```typescript
function sortBy<T extends object>(collection: T[], iteratees: Array<Iteratee<T>> | Array<keyof T>): T[]; function sortBy<T extends object>(arr: T[], criteria: Array<keyof T | ((item: T) => unknown)>): T[];
``` ```
### Parameters ### Parameters
- `collection` (`T[]`): The array of objects to be sorted. - `arr` (`T[]`): The array of objects to be sorted.
- `iteratees` (`Array<Iteratee<T>> | Array<keyof T>`): The array of iteratees or keys to sort by. - `criteria` (`Array<keyof T | ((item: T) => unknown)>`): The criteria for sorting. This can be an array of object keys or functions that return values used for sorting.
### Returns ### Returns
(`T[]`) The ascendingly sorted array of objects. (`T[]`) The ascendingly sorted array of objects.
## Examples ## Example
```typescript ```typescript
const users = [ const users = [

View File

@ -0,0 +1,44 @@
# sortBy
根据给定的 `criteria` 对对象数组进行排序。
- 如果提供的是键,它将根据这些键的值对对象进行排序。
- 如果提供的是函数,它将根据这些函数返回的值进行排序。
该函数返回按升序排列的对象数组。如果两个对象在当前标准下具有相同的值,它将使用下一个标准来确定它们的顺序。
## 签名
```typescript
function sortBy<T extends object>(arr: T[], criteria: Array<keyof T | ((item: T) => unknown)>): T[];
```
### 参数
- `arr` (`T[]`): 要排序的对象数组。
- `criteria` (`Array<keyof T | ((item: T) => unknown)>`): 排序标准。可以是对象键的数组或返回用于排序的值的函数数组。
### 返回值
(`T[]`): 按升序排序的对象数组。
## 示例
```typescript
const users = [
{ user: 'foo', age: 24 },
{ user: 'bar', age: 7 },
{ user: 'foo ', age: 8 },
{ user: 'bar ', age: 29 },
];
sortBy(users, ['user', 'age']);
sortBy(users, [obj => obj.user, obj => obj.age]);
// results will be:
// [
// { user : 'bar', age: 7 },
// { user : 'bar', age: 29 },
// { user : 'foo', age: 8 },
// { user : 'foo', age: 24 },
// ]
```

View File

@ -0,0 +1,9 @@
export function compareValues(a: any, b: any): 0 | -1 | 1 {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}

View File

@ -1,18 +1,17 @@
type Iteratee<T> = (object: T) => T[keyof T]; import { compareValues } from '../_internal/compareValues';
/** /**
* Sorts an array of objects based on the given iteratees or keys in ascending order. * Sorts an array of objects based on the given `criteria`.
* *
* This function takes an array of objects, an array of iteratees (or keys) to sort by. * - If you provide keys, it sorts the objects by the values of those keys.
* It returns the ascendingly sorted array of objects. * - If you provide functions, it sorts based on the values returned by those functions.
* If `iteratees` are keys of the object, it sorts based on the values of the keys. *
* If `iteratees` are iteratee functions, it sorts based on the return values of the functions. * The function returns the array of objects sorted in ascending order.
* If values for a key are equal, it moves to the next key to determine the order. * If two objects have the same value for the current criterion, it uses the next criterion to determine their order.
* *
* @template T - The type of the objects in the array. * @template T - The type of the objects in the array.
* @param {T[]} collection - The array of objects to be sorted. * @param {T[]} arr - The array of objects to be sorted.
* @param {Array<Iteratee<T> | keyof T>} iteratees - The array of iteratees or keys to sort by. * @param {Array<(item: T) => unknown | keyof T>} criteria - The criteria for sorting. This can be an array of object keys or functions that return values used for sorting.
* @returns {T[]} The ascendingly sorted array of objects.
* *
* @example * @example
* const users = [ * const users = [
@ -32,22 +31,10 @@ type Iteratee<T> = (object: T) => T[keyof T];
* // { user : 'foo', age: 24 }, * // { user : 'foo', age: 24 },
* // ] * // ]
*/ */
export function sortBy<T extends object>(collection: T[], iteratees: Array<Iteratee<T> | keyof T>): T[] { export function sortBy<T extends object>(arr: T[], criteria: Array<(item: T) => unknown | keyof T>): T[] {
const compareValues = (a: T[keyof T], b: T[keyof T]) => { return arr.slice().sort((a, b) => {
if (a < b) { for (let i = 0; i < criteria.length; i++) {
return -1; const iteratee = criteria[i];
}
if (a > b) {
return 1;
}
return 0;
};
return collection.slice().sort((a, b) => {
for (let i = 0; i < iteratees.length; i++) {
const iteratee = iteratees[i];
const iterateeIsFunction = typeof iteratee === 'function'; const iterateeIsFunction = typeof iteratee === 'function';
const valueA = iterateeIsFunction ? iteratee(a) : a[iteratee]; const valueA = iterateeIsFunction ? iteratee(a) : a[iteratee];