docs: Add docs for replace, iteratee, and differenceBy (compat)

This commit is contained in:
Sojin Park 2024-10-26 19:57:14 +09:00
parent c5fa2654a4
commit 9936d10699
10 changed files with 460 additions and 5 deletions

View File

@ -0,0 +1,38 @@
# replace
::: info
この関数は互換性のために `es-toolkit/compat` からのみインポートできます。代替可能なネイティブ JavaScript API があるか、まだ十分に最適化されていないためです。
`es-toolkit/compat` からこの関数をインポートすると、[lodash と完全に同じように動作](../../../compatibility.md)します。
:::
文字列内の一致するパターンを別の文字列に置き換えます。
## インターフェース
```typescript
function replace(
target: string,
pattern: string | RegExp,
replacement: string | ((substring: string, ...args: any[]) => string)
): string;
```
### パラメータ
- `target` (`string`): 対象の文字列。
- `pattern` (`string | RegExp`): 一致させるパターン。
- `replacement` (`string | ((substring: string, ...args: any[]) => string)`): 置換文字列または置換文字列を返す関数。
### 戻り値
(`string`): 一致したパターンが置き換えられた新しい文字列。
## 例
```typescript
replace('abcde', 'de', '123'); // 'abc123'
replace('abcde', /[bd]/g, '-'); // 'a-c-e'
replace('abcde', 'de', substring => substring.toUpperCase()); // 'abcDE'
replace('abcde', /[bd]/g, substring => substring.toUpperCase()); // 'aBcDe'
```

View File

@ -0,0 +1,49 @@
# iteratee
::: info
この関数は互換性のために `es-toolkit/compat` からのみインポートできます。代替可能なネイティブ JavaScript API があるか、まだ十分に最適化されていないためです。
`es-toolkit/compat` からこの関数をインポートすると、[lodash と完全に同じように動作](../../../compatibility.md)します。
:::
コレクションの要素から値を返す関数を作成します。
`iteratee` 関数に渡される引数の種類によって、返される関数の動作が異なります。
- **関数**: 渡された関数をそのまま返します。
- **プロパティ名**: 要素から指定されたプロパティの値を返します。
- **プロパティ-値のペア**: 要素のプロパティが指定された値と一致するかどうかを示すブール値を返します。
- **部分オブジェクト**: 要素が部分オブジェクトのプロパティと値に一致するかどうかを示すブール値を返します。
引数を提供しないか、`null` を渡すと、この関数は [要素をそのまま返す関数](../../function/identity.md) を返します。
## インターフェース
```typescript
function iteratee(value?: null): (value: T) => T;
function iteratee<F extends (...args: any[]) => unknown>(func: F): F;
function iteratee(value: symbol | number | string | object): (...args: any[]) => any;
```
### パラメータ
- `value` (`symbol | number | string | object | null | ((...args: any[]) => any)`): 反復子に変換する値。
### 戻り値
(`(...args: any[]) => unknown`): 新しい反復子関数。
## 例
```typescript
const func = iteratee();
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [{ a: 1 }, { a: 2 }, { a: 3 }]
const func = iteratee((object) => object.a);
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [1, 2, 3]
const func = iteratee('a');
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [1, 2, 3]
```

View File

@ -0,0 +1,38 @@
# replace
::: info
이 함수는 호환성을 위한 `es-toolkit/compat` 에서만 가져올 수 있어요. 대체할 수 있는 네이티브 JavaScript API가 있거나, 아직 충분히 최적화되지 않았기 때문이에요.
`es-toolkit/compat`에서 이 함수를 가져오면, [lodash와 완전히 똑같이 동작](../../../compatibility.md)해요.
:::
문자열에서 일치하는 패턴을 다른 문자열로 바꿔요.
## 인터페이스
```typescript
function replace(
target: string,
pattern: string | RegExp,
replacement: string | ((substring: string, ...args: any[]) => string)
): string;
```
### 파라미터
- `target` (`string`): 대상 문자열.
- `pattern` (`string | RegExp`): 일치시킬 패턴.
- `replacement` (`string | ((substring: string, ...args: any[]) => string)`): 교체 문자열 또는 교체 문자열을 반환하는 함수.
### 반환 값
(`string`): 일치한 패턴이 대체된 새로운 문자열.
## 예시
```typescript
replace('abcde', 'de', '123'); // 'abc123'
replace('abcde', /[bd]/g, '-'); // 'a-c-e'
replace('abcde', 'de', substring => substring.toUpperCase()); // 'abcDE'
replace('abcde', /[bd]/g, substring => substring.toUpperCase()); // 'aBcDe'
```

View File

@ -0,0 +1,53 @@
# iteratee
::: info
이 함수는 호환성을 위한 `es-toolkit/compat` 에서만 가져올 수 있어요. 대체할 수 있는 네이티브 JavaScript API가 있거나, 아직 충분히 최적화되지 않았기 때문이에요.
`es-toolkit/compat`에서 이 함수를 가져오면, [lodash와 완전히 똑같이 동작](../../../compatibility.md)해요.
:::
요소에서 값을 반환하는 함수를 만들어요.
`iteratee` 함수에 주어지는 파라미터의 종류에 따라서 반환하는 함수의 동작이 달라져요.
- **함수**: 주어진 함수를 있는 그대로 반환해요.
- **속성 이름**: 요소에서 주어진 프로퍼티의 값을 반환해요.
- **속성-값 쌍**: 요소의 속성이 주어진 값과 일치하는지 여부를 나타내는 참/거짓 값을 반환해요.
- **부분 객체**: 요소가 부분 객체의 프로퍼티와 값에 일치하는지 여부를 나타내는 참/거짓 값을 반환해요.
아무 인수도 제공하지 않거나 `null`을 전달하면, 이 함수는 [요소를 있는 그대로 반환하는 함수](../../function/identity.md)를 반환해요.
## 인터페이스
```typescript
function iteratee(value?: null): (value: T) => T;
function iteratee<F extends (...args: any[]) => unknown>(func: F): F;
function iteratee(value: symbol | number | string | object): (...args: any[]) => any;
function iteratee(
value?: symbol | number | string | object | null | ((...args: any[]) => unknown)
): (...args: any[]) => any;
```
### 파라미터
- `value` (`symbol | number | string | object | null | ((...args: any[]) => any)`): iteratee로 변환할 값이에요. 문자열.
### 반환 값
(`(...args: any[]) => unknown`): 새로운 iteratee 함수를 반환해요. 문자열.
## 예시
```typescript
const func = iteratee();
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [{ a: 1 }, { a: 2 }, { a: 3 }]
const func = iteratee((object) => object.a);
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [1, 2, 3]
const func = iteratee('a');
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [1, 2, 3]
```

View File

@ -0,0 +1,38 @@
# replace
::: info
This function is only available in `es-toolkit/compat` for compatibility reasons. It either has alternative native JavaScript APIs or isnt fully optimized yet.
When imported from `es-toolkit/compat`, it behaves exactly like lodash and provides the same functionalities, as detailed [here](../../../compatibility.md).
:::
Replaces the matched pattern with the replacement string.
## Signature
```typescript
function replace(
target: string,
pattern: string | RegExp,
replacement: string | ((substring: string, ...args: any[]) => string)
): string;
```
### Parameters
- `target` (`string`): The target string.
- `pattern` (`string | RegExp`): The pattern to match.
- `replacement` (`string | ((substring: string, ...args: any[]) => string)`): The replacement string or a function that returns the replacement string.
### Returns
(`string`): The new string with the matched pattern replaced.
## Examples
```typescript
replace('abcde', 'de', '123'); // 'abc123'
replace('abcde', /[bd]/g, '-'); // 'a-c-e'
replace('abcde', 'de', substring => substring.toUpperCase()); // 'abcDE'
replace('abcde', /[bd]/g, substring => substring.toUpperCase()); // 'aBcDe'
```

View File

@ -0,0 +1,53 @@
# iteratee
::: info
This function is only available in `es-toolkit/compat` for compatibility reasons. It either has alternative native JavaScript APIs or isnt fully optimized yet.
When imported from `es-toolkit/compat`, it behaves exactly like lodash and provides the same functionalities, as detailed [here](../../../compatibility.md).
:::
Creates a function that returns a value from an element in a collection.
You can call `iteratee` with the following types of arguments:
- **Function**: Returns the function as-is, which will be called with the element from the collection.
- **Property name**: Returns the value of the specified property from the element.
- **Property-value pair**: Returns a boolean indicating whether the element's property matches the given value.
- **Partial object**: Returns a boolean indicating whether the element matches the properties of the partial object.
If you don't provide any arguments or pass `null`, this function will return a function that simply returns its input unchanged.
## Signature
```typescript
function iteratee(value?: null): <T>(value: T) => T;
function iteratee<F extends (...args: any[]) => unknown>(func: F): F;
function iteratee(value: symbol | number | string | object): (...args: any[]) => any;
function iteratee(
value?: symbol | number | string | object | null | ((...args: any[]) => unknown)
): (...args: any[]) => any;
```
### Parameters
- `value` (`symbol | number | string | object | null | ((...args: any[]) => any)`): The value to convert to an iteratee.
### Returns
(`(...args: any[]) => unknown`): Returns the new iteratee function.
## Examples
```typescript
const func = iteratee();
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [{ a: 1 }, { a: 2 }, { a: 3 }]
const func = iteratee((object) => object.a);
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [1, 2, 3]
const func = iteratee('a');
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [1, 2, 3]
```

View File

@ -0,0 +1,38 @@
# replace
::: info
出于兼容性原因,此函数仅在 `es-toolkit/compat` 中提供。它可能具有替代的原生 JavaScript API或者尚未完全优化。
`es-toolkit/compat` 导入时,它的行为与 lodash 完全一致,并提供相同的功能,详情请见 [这里](../../../compatibility.md)。
:::
用替换字符串替换匹配的模式。
## 签名
```typescript
function replace(
target: string,
pattern: string | RegExp,
replacement: string | ((substring: string, ...args: any[]) => string)
): string;
```
### 参数
- `target` (`string`): 目标字符串。
- `pattern` (`string | RegExp`): 要匹配的模式。
- `replacement` (`string | ((substring: string, ...args: any[]) => string)`): 替换字符串或返回替换字符串的函数。
### 返回值
(`string`): 用匹配模式替换后的新字符串。
## 示例
```typescript
replace('abcde', 'de', '123'); // 'abc123'
replace('abcde', /[bd]/g, '-'); // 'a-c-e'
replace('abcde', 'de', substring => substring.toUpperCase()); // 'abcDE'
replace('abcde', /[bd]/g, substring => substring.toUpperCase()); // 'aBcDe'
```

View File

@ -0,0 +1,52 @@
# iteratee
::: info
出于兼容性原因,此函数仅在 `es-toolkit/compat` 中提供。它可能具有替代的原生 JavaScript API或者尚未完全优化。
`es-toolkit/compat` 导入时,它的行为与 lodash 完全一致,并提供相同的功能,详情请见 [这里](../../../compatibility.md)。
:::
创建一个函数,该函数从集合中的元素返回一个值。
你可以使用以下类型的参数调用 `iteratee`
- **函数**: 返回原样的函数,该函数将使用集合中的元素进行调用。
- **属性名**: 返回元素中指定属性的值。
- **属性-值对**: 返回一个布尔值,指示元素的属性是否与给定值匹配。
- **部分对象**: 返回一个布尔值,指示元素是否与部分对象的属性匹配。
如果你不提供任何参数或传递 `null`,此函数将返回一个简单返回其输入的函数。
## 签名
```typescript
function iteratee(value?: null): (value: T) => T;
function iteratee<F extends (...args: any[]) => unknown>(func: F): F;
function iteratee(value: symbol | number | string | object): (...args: any[]) => any;
function iteratee(
value?: symbol | number | string | object | null | ((...args: any[]) => unknown)
): (...args: any[]) => any;
```
### 参数
- `value` (`symbol | number | string | object | null | ((...args: any[]) => any)`): 将要转换为迭代器的值。
### 返回值
(`(...args: any[]) => unknown`): 返回新的迭代器函数。
## 示例
```typescript
const func = iteratee();
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [{ a: 1 }, { a: 2 }, { a: 3 }]
const func = iteratee((object) => object.a);
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [1, 2, 3]
const func = iteratee('a');
[{ a: 1 }, { a: 2 }, { a: 3 }].map(func) // => [1, 2, 3]
```

View File

@ -7,12 +7,43 @@ import { iteratee as createIteratee } from '../util/iteratee.ts';
type Iteratee<T> = PropertyKey | Partial<T> | ((value: T) => unknown);
/**
* Computes the difference between an array and another array using an iteratee function.
*
* @template T1, T2
* @param {ArrayLike<T1> | null | undefined} array - The primary array from which to derive the difference.
* @param {ArrayLike<T2>} values - The array containing elements to be excluded from the primary array.
* @param {Iteratee<T1 | T2>} iteratee - The iteratee invoked per element.
* @returns {T1[]} A new array containing the elements that are present in the primary array but not in the values array.
*
* @example
* const result = differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // result will be [1.2]
*
* @example
* const result = differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], 'x');
* // result will be [{ x: 2 }]
*/
export function differenceBy<T1, T2>(
array: ArrayLike<T1> | null | undefined,
values: ArrayLike<T2>,
iteratee: Iteratee<T1 | T2>
): T1[];
/**
* Computes the difference between an array and two other arrays using an iteratee function.
*
* @template T1, T2, T3
* @param {ArrayLike<T1> | null | undefined} array - The primary array from which to derive the difference.
* @param {ArrayLike<T2>} values1 - The first array containing elements to be excluded from the primary array.
* @param {ArrayLike<T3>} values2 - The second array containing elements to be excluded from the primary array.
* @param {Iteratee<T1 | T2 | T3>} iteratee - The iteratee invoked per element.
* @returns {T1[]} A new array containing the elements that are present in the primary array but not in the values arrays.
*
* @example
* const result = differenceBy([2.1, 1.2], [2.3, 3.4], [1.2], Math.floor);
* // result will be []
*/
export function differenceBy<T1, T2, T3>(
array: ArrayLike<T1> | null | undefined,
values1: ArrayLike<T2>,
@ -20,6 +51,21 @@ export function differenceBy<T1, T2, T3>(
iteratee: Iteratee<T1 | T2 | T3>
): T1[];
/**
* Computes the difference between an array and three other arrays using an iteratee function.
*
* @template T1, T2, T3, T4
* @param {ArrayLike<T1> | null | undefined} array - The primary array from which to derive the difference.
* @param {ArrayLike<T2>} values1 - The first array containing elements to be excluded from the primary array.
* @param {ArrayLike<T3>} values2 - The second array containing elements to be excluded from the primary array.
* @param {ArrayLike<T4>} values3 - The third array containing elements to be excluded from the primary array.
* @param {Iteratee<T1 | T2 | T3 | T4>} iteratee - The iteratee invoked per element.
* @returns {T1[]} A new array containing the elements that are present in the primary array but not in the values arrays.
*
* @example
* const result = differenceBy([2.1, 1.2], [2.3, 3.4], [1.2], [2.1], Math.floor);
* // result will be []
*/
export function differenceBy<T1, T2, T3, T4>(
array: ArrayLike<T1> | null | undefined,
values1: ArrayLike<T2>,
@ -28,6 +74,22 @@ export function differenceBy<T1, T2, T3, T4>(
iteratee: Iteratee<T1 | T2 | T3 | T4>
): T1[];
/**
* Computes the difference between an array and four other arrays using an iteratee function.
*
* @template T1, T2, T3, T4, T5
* @param {ArrayLike<T1> | null | undefined} array - The primary array from which to derive the difference.
* @param {ArrayLike<T2>} values1 - The first array containing elements to be excluded from the primary array.
* @param {ArrayLike<T3>} values2 - The second array containing elements to be excluded from the primary array.
* @param {ArrayLike<T4>} values3 - The third array containing elements to be excluded from the primary array.
* @param {ArrayLike<T5>} values4 - The fourth array containing elements to be excluded from the primary array.
* @param {Iteratee<T1 | T2 | T3 | T4 | T5>} iteratee - The iteratee invoked per element.
* @returns {T1[]} A new array containing the elements that are present in the primary array but not in the values arrays.
*
* @example
* const result = differenceBy([2.1, 1.2], [2.3, 3.4], [1.2], [2.1], [3.4], Math.floor);
* // result will be []
*/
export function differenceBy<T1, T2, T3, T4, T5>(
array: ArrayLike<T1> | null | undefined,
values1: ArrayLike<T2>,
@ -37,8 +99,28 @@ export function differenceBy<T1, T2, T3, T4, T5>(
iteratee: Iteratee<T1 | T2 | T3 | T4 | T5>
): T1[];
/**
* Computes the difference between an array and multiple arrays using an iteratee function.
*
* @template T
* @param {ArrayLike<T> | null | undefined} array - The primary array from which to derive the difference.
* @param {...Array<ArrayLike<T>>} values - Multiple arrays containing elements to be excluded from the primary array.
* @returns {T[]} A new array containing the elements that are present in the primary array but not in the values arrays.
*
* @example
* const result = differenceBy([2.1, 1.2], [2.3, 3.4], [1.2], [2.1], [3.4], Math.floor);
* // result will be []
*/
export function differenceBy<T>(array: ArrayLike<T> | null | undefined, ...values: Array<ArrayLike<T>>): T[];
/**
* Computes the difference between an array and multiple arrays using an iteratee function.
*
* @template T
* @param {ArrayLike<T> | null | undefined} arr - The primary array from which to derive the difference.
* @param {...any[]} values - Multiple arrays containing elements to be excluded from the primary array.
* @returns {T[]} A new array containing the elements that are present in the primary array but not in the values arrays.
*/
export function differenceBy<T>(arr: ArrayLike<T> | null | undefined, ...values: any[]): T[] {
if (!isArrayLikeObject(arr)) {
return [];

View File

@ -46,10 +46,16 @@ export function iteratee<F extends (...args: any[]) => unknown>(func: F): F;
export function iteratee(value: symbol | number | string | object): (...args: any[]) => any;
/**
* Creates a function that invokes `value` with the arguments of the created function.
* Creates a function that returns a value from an element in a collection.
*
* - If `value` is a property name, the created function returns the property value for a given element.
* - If `value` is an array or object, the created function returns `true` for elements that contain the equivalent source properties, otherwise `false`.
* You can call `iteratee` with the following types of arguments:
*
* - **Function**: Returns the function as-is, which will be called with the element from the collection.
* - **Property name**: Returns the value of the specified property from the element.
* - **Property-value pair**: Returns a boolean indicating whether the element's property matches the given value.
* - **Partial object**: Returns a boolean indicating whether the element matches the properties of the partial object.
*
* If you don't provide any arguments or pass `null`, this function will return a function that simply returns its input unchanged.
*
* @param {symbol | number | string | object | null | ((...args: any[]) => any)} value - The value to convert to an iteratee.
* @returns {(...args: any[]) => unknown} - Returns the new iteratee function.
@ -78,8 +84,16 @@ export function iteratee(
return value as any;
}
case 'object': {
return Array.isArray(value) ? matchesProperty(value[0], value[1]) : matches(value);
if (Array.isArray(value) && value.length === 2) {
return matchesProperty(value[0], value[1]);
}
return matches(value);
}
case 'string':
case 'symbol':
case 'number': {
return property(value);
}
}
return property(value);
}