Skip to content

Commit

Permalink
feat(nthArg): Add nthArg to compat (#887)
Browse files Browse the repository at this point in the history
  • Loading branch information
mass2527 authored Dec 8, 2024
1 parent eb0e32d commit 77c3509
Show file tree
Hide file tree
Showing 8 changed files with 283 additions and 0 deletions.
34 changes: 34 additions & 0 deletions benchmarks/performance/nthArg.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { bench, describe } from 'vitest';
import { nthArg as nthArgToolkitCompat_ } from 'es-toolkit/compat';
import { nthArg as nthArgLodash_ } from 'lodash';

const nthArgToolkitCompat = nthArgToolkitCompat_;
const nthArgLodash = nthArgLodash_;

describe('nthArg', () => {
const array = [1, 2, 3];

bench('es-toolkit/compat/nthArg', () => {
nthArgToolkitCompat(0)(...array);
nthArgToolkitCompat(-1)(...array);
});

bench('lodash/nthArg', () => {
nthArgLodash(0)(...array);
nthArgLodash(-1)(...array);
});
});

describe('nthArg/largeArray', () => {
const largeArray = Array.from({ length: 10000 }, (_, i) => i);

bench('es-toolkit/compat/nthArg', () => {
nthArgToolkitCompat(0)(...largeArray);
nthArgToolkitCompat(-1)(...largeArray);
});

bench('lodash/nthArg', () => {
nthArgLodash(0)(...largeArray);
nthArgLodash(-1)(...largeArray);
});
});
38 changes: 38 additions & 0 deletions docs/ja/reference/compat/function/nthArg.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# nthArg

::: info
この関数は互換性のために `es-toolkit/compat` からのみインポートできます。代替可能なネイティブ JavaScript API があるか、まだ十分に最適化されていないためです。

`es-toolkit/compat` からこの関数をインポートすると、[lodash と完全に同じように動作](../../../compatibility.md)します。
:::

指定されたインデックス `n` にある引数を取得する関数を作成します。

`n` が負の場合、末尾から数えて n 番目の引数が返ります。文字列。

## インターフェース

```typescript
function nthArg(n: number): (...args: any[]) => unknown;
```

### パラメータ

- `n` (`number`): 取得する引数のインデックス。
負の場合、引数リストの末尾から数えます。文字列。

### 戻り値

(`(args: any[]) => unknown`): 指定されたインデックスの引数を返す新しい関数です。文字列。

##

```typescript
const getSecondArg = nthArg(1);
const result = getSecondArg('a', 'b', 'c');
console.log(result); // => 'b'

const getLastArg = nthArg(-1);
const result = getLastArg('a', 'b', 'c');
console.log(result); // => 'c'
```
38 changes: 38 additions & 0 deletions docs/ko/reference/compat/function/nthArg.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# nthArg

::: info
이 함수는 호환성을 위한 `es-toolkit/compat` 에서만 가져올 수 있어요. 대체할 수 있는 네이티브 JavaScript API가 있거나, 아직 충분히 최적화되지 않았기 때문이에요.

`es-toolkit/compat`에서 이 함수를 가져오면, [lodash와 완전히 똑같이 동작](../../../compatibility.md)해요.
:::

지정된 인덱스 `n`에서 인수를 검색하는 함수를 생성해요.

`n`이 음수이면, 끝에서부터 인수가 반환돼요.

## 인터페이스

```typescript
function nthArg(n: number): (...args: any[]) => unknown;
```

### 파라미터

- `n` (`number`): 검색할 인수의 인덱스.
음수이면 인수 목록의 끝에서부터 계산해요.

### 반환 값

(`(args: any[]) => unknown`): 지정된 인덱스의 인수를 반환하는 함수.

## 예시

```typescript
const getSecondArg = nthArg(1);
const result = getSecondArg('a', 'b', 'c');
console.log(result); // => 'b'

const getLastArg = nthArg(-1);
const result = getLastArg('a', 'b', 'c');
console.log(result); // => 'c'
```
38 changes: 38 additions & 0 deletions docs/reference/compat/function/nthArg.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# nthArg

::: info
This function is only available in `es-toolkit/compat` for compatibility reasons. It either has alternative native JavaScript APIs or isn’t 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 retrieves the argument at the specified index `n`.

If `n` is negative, the nth argument from the end is returned.

## Signature

```typescript
function nthArg(n: number): (...args: any[]) => unknown;
```

### Parameters

- `n` (`number`): The index of the argument to retrieve.
If negative, counts from the end of the arguments list.

### Returns

(`(args: any[]) => unknown`): A new function that returns the argument at the specified index.

## Examples

```typescript
const getSecondArg = nthArg(1);
const result = getSecondArg('a', 'b', 'c');
console.log(result); // => 'b'

const getLastArg = nthArg(-1);
const result = getLastArg('a', 'b', 'c');
console.log(result); // => 'c'
```
38 changes: 38 additions & 0 deletions docs/zh_hans/reference/compat/function/nthArg.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# nthArg

::: info
出于兼容性原因,此函数仅在 `es-toolkit/compat` 中提供。它可能具有替代的原生 JavaScript API,或者尚未完全优化。

`es-toolkit/compat` 导入时,它的行为与 lodash 完全一致,并提供相同的功能,详情请见 [这里](../../../compatibility.md)
:::

创建一个函数,用于检索指定索引 `n` 处的参数。

如果 `n` 为负数,则返回从末尾开始的第 n 个参数。

## 签名

```typescript
function nthArg(n: number): (...args: any[]) => unknown;
```

### 参数

- `n` (`number`): 要检索的参数的索引。
如果为负,则从参数列表的末尾开始计数。

### 返回值

(`(args: any[]) => unknown`): 一个新函数,返回指定索引处的参数。

## 示例

```typescript
const getSecondArg = nthArg(1);
const result = getSecondArg('a', 'b', 'c');
console.log(result); // => 'b'

const getLastArg = nthArg(-1);
const result = getLastArg('a', 'b', 'c');
console.log(result); // => 'c'
```
70 changes: 70 additions & 0 deletions src/compat/function/nthArg.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest';
import { nthArg } from './nthArg';
import { noop } from '../../function';
import { range } from '../../math';
import { falsey } from '../_internal/falsey';
import { stubA } from '../_internal/stubA';
import { stubB } from '../_internal/stubB';

describe('nthArg', () => {
const args = ['a', 'b', 'c', 'd'];

it('should create a function that returns its nth argument', () => {
const actual = args.map((value, index) => {
const func = nthArg(index);
return func(...args);
});

expect(actual).toEqual(args);
});

it('should work with a negative `n`', () => {
const actual = range(1, args.length + 1).map(n => {
const func = nthArg(-n);
return func(...args);
});

expect(actual).toEqual(['d', 'c', 'b', 'a']);
});

it('should coerce `n` to an integer', () => {
let values = falsey;
let expected = values.map(stubA);

let actual = values.map(n => {
// @ts-expect-error invalid types
const func = n ? nthArg(n) : nthArg();
return func(...args);
});

expect(actual).toEqual(expected);

values = ['1', 1.6];
expected = values.map(stubB);

actual = values.map(n => {
// @ts-expect-error invalid types
const func = nthArg(n);
return func(...args);
});

expect(actual).toEqual(expected);
});

it('should return `undefined` for empty arrays', () => {
const func = nthArg(1);
expect(func()).toBe(undefined);
});

it('should return `undefined` for non-indexes', () => {
const values = [Infinity, args.length];
const expected = values.map(noop);

const actual = values.map(n => {
const func = nthArg(n);
return func(...args);
});

expect(actual).toEqual(expected);
});
});
26 changes: 26 additions & 0 deletions src/compat/function/nthArg.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { toInteger } from '../util/toInteger.ts';

/**
* Creates a function that retrieves the argument at the specified index `n`.
*
* If `n` is negative, the nth argument from the end is returned.
*
* @param {number} [n=0] - The index of the argument to retrieve.
* If negative, counts from the end of the arguments list.
* @returns {(args: any[]) => unknown} A new function that returns the argument at the specified index.
*
* @example
* const getSecondArg = nthArg(1);
* const result = getSecondArg('a', 'b', 'c');
* console.log(result); // => 'b'
*
* @example
* const getLastArg = nthArg(-1);
* const result = getLastArg('a', 'b', 'c');
* console.log(result); // => 'c'
*/
export function nthArg(n = 0): (...args: any[]) => unknown {
return function (...args: any[]) {
return args.at(toInteger(n));
};
}
1 change: 1 addition & 0 deletions src/compat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export { defer } from './function/defer.ts';
export { flip } from './function/flip.ts';
export { flow } from './function/flow.ts';
export { flowRight } from './function/flowRight.ts';
export { nthArg } from './function/nthArg.ts';
export { rearg } from './function/rearg.ts';
export { rest } from './function/rest.ts';
export { spread } from './function/spread.ts';
Expand Down

0 comments on commit 77c3509

Please sign in to comment.