Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(findKey): add findKey #755

Merged
merged 8 commits into from
Nov 3, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions benchmarks/performance/findKey.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { bench, describe } from 'vitest';
import { findKey as findKeyToolkit } from 'es-toolkit';
import { findKey as findKeyLodash } from 'lodash';

describe('findKey', () => {
const users = {
pebbles: { age: 24, active: true },
barney: { age: 36, active: true },
fred: { age: 40, active: false },
};

bench('es-toolkit/findKey', () => {
findKeyToolkit(users, o => o.age < 40);
});

bench('lodash/findKey', () => {
findKeyLodash(users, o => o.age < 40);
});
});

describe('findKey/largeObject', () => {
const largeUsers: Record<string, { age: number }> = {};
for (let i = 0; i < 10000; i++) {
largeUsers[`user${i}`] = { age: Number(i) };
}

bench('es-toolkit/findKey', () => {
findKeyToolkit(largeUsers, o => o.age === 7000);
});

bench('lodash/findKey', () => {
findKeyLodash(largeUsers, o => o.age === 7000);
});
});
34 changes: 34 additions & 0 deletions docs/ja/reference/object/findKey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# findKey
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We actually generate documents in an automated way; you don't have to manually create them.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@raon0211 Oh, I see... I guess I won't have to write docs from next time.


提供されたテスト関数を満たすオブジェクト内の最初の要素のキーを検索します。

## Signature

```typescript
function findKey<T extends Record<any, any>>(
obj: T,
predicate: (value: T[keyof T], key: keyof T, obj: T) => boolean
): keyof T | undefined;
```

### Parameters

- `obj` (`T extends Record<any, any>`): 検索するオブジェクト。
- `predicate` (`(value: T[keyof T], key: keyof T, obj: T) => boolean`): オブジェクト内の各値に対して実行する関数。

### Returns

(`keyof T | undefined`): 指定されたテスト関数を満たすオブジェクト内の最初の要素のキー。テストに合格する要素がない場合は未定義です。

## Examples

```typescript
const users = {
pebbles: { age: 24, active: true },
barney: { age: 36, active: true },
fred: { age: 40, active: false },
};

findKey(users, o => o.age < 40); // 'pebbles'
findKey(users, o => o.age > 50); // undefined
```
34 changes: 34 additions & 0 deletions docs/ko/reference/object/findKey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# findKey

인자로 받은 함수를 만족하는 첫 번째 요소의 키를 반환해요.

## 인터페이스

```typescript
function findKey<T extends Record<any, any>>(
obj: T,
predicate: (value: T[keyof T], key: keyof T, obj: T) => boolean
): keyof T | undefined;
```

### 파라미터

- `obj` (`T extends Record<any, any>`): 탐색할 객체예요.
- `predicate` (`(value: T[keyof T], key: keyof T, obj: T) => boolean`): 객체의 각 값에 대해 실행할 함수에요.

### 반환 값

(`keyof T | undefined`): 인자로 받은 함수를 만족하는 첫 번째 요소의 키에요. 함수를 만족하는 요소가 없으면 undefined를 반환해요.

## 예시

```typescript
const users = {
pebbles: { age: 24, active: true },
barney: { age: 36, active: true },
fred: { age: 40, active: false },
};

findKey(users, o => o.age < 40); // 'pebbles'
findKey(users, o => o.age > 50); // undefined
```
34 changes: 34 additions & 0 deletions docs/reference/object/findKey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# findKey

Finds the key of the first element in the object that satisfies the provided testing function.

## Signature

```typescript
function findKey<T extends Record<any, any>>(
obj: T,
predicate: (value: T[keyof T], key: keyof T, obj: T) => boolean
): keyof T | undefined;
```

### Parameters

- `obj` (`T extends Record<any, any>`): The object to search.
- `predicate` (`(value: T[keyof T], key: keyof T, obj: T) => boolean`): The function to execute on each value in the object.

### Returns

(`keyof T | undefined`): The key of the first element in the object that satisfies the provided testing function, or undefined if no element passes the test.

## Examples

```typescript
const users = {
pebbles: { age: 24, active: true },
barney: { age: 36, active: true },
fred: { age: 40, active: false },
};

findKey(users, o => o.age < 40); // 'pebbles'
findKey(users, o => o.age > 50); // undefined
```
34 changes: 34 additions & 0 deletions docs/zh_hans/reference/object/findKey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# findKey

查找对象中满足所提供的测试函数的第一个元素的键。

## Signature

```typescript
function findKey<T extends Record<any, any>>(
obj: T,
predicate: (value: T[keyof T], key: keyof T, obj: T) => boolean
): keyof T | undefined;
```

### Parameters

- `obj` (`T extends Record<any, any>`): 要搜索的对象。
- `predicate` (`(value: T[keyof T], key: keyof T, obj: T) => boolean`): 对对象中的每个值执行的函数。

### Returns

(`keyof T | undefined`): 对象中满足所提供的测试功能的第一个元素的键,如果没有元素通过测试,则为未定义。

## Examples

```typescript
const users = {
pebbles: { age: 24, active: true },
barney: { age: 36, active: true },
fred: { age: 40, active: false },
};

findKey(users, o => o.age < 40); // 'pebbles'
findKey(users, o => o.age > 50); // undefined
```
48 changes: 48 additions & 0 deletions src/object/findKey.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest';
import { findKey } from './findKey';

describe('findKey', () => {
const users = {
pebbles: { age: 24, active: true },
barney: { age: 36, active: true },
fred: { age: 40, active: false },
};

it('should return the key of the first element that satisfies the predicate', () => {
expect(findKey(users, o => o.age < 40)).toBe('pebbles');
});

it('should return the first key if all elements satisfy the predicate', () => {
expect(findKey(users, o => o.age > 20)).toBe('pebbles');
});

it('should return undefined if no element satisfies the predicate', () => {
expect(findKey(users, o => o.age > 50)).toBeUndefined();
});

it('should return undefined for an empty object', () => {
const users = {};

// @ts-expect-error
expect(findKey(users, o => o.age < 40)).toBeUndefined();
});

it('should handle objects with various data types', () => {
const data = {
num: 42,
str: 'hello',
bool: true,
};

expect(findKey(data, value => typeof value === 'string')).toBe('str');
});

it('should pass the key and object to the predicate function', () => {
const users = {
barney: { age: 36, active: true },
fred: { age: 40, active: false },
};

expect(findKey(users, (value, key, obj) => key === 'fred' && obj[key].active === false)).toBe('fred');
});
});
26 changes: 26 additions & 0 deletions src/object/findKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Finds the key of the first element in the object that satisfies the provided testing function.
*
* @param obj - The object to search.
* @param predicate - The function to execute on each value in the object. It takes three arguments:
* - value: The current value being processed in the object.
* - key: The key of the current value being processed in the object.
* - obj: The object that findKey was called upon.
* @returns The key of the first element in the object that passes the test, or undefined if no element passes.
*
* @example
* const users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
* findKey(users, function(o) { return o.age < 40; }); => 'barney'
*/
export function findKey<T extends Record<any, any>>(
obj: T,
predicate: (value: T[keyof T], key: keyof T, obj: T) => boolean
): keyof T | undefined {
const keys = Object.keys(obj) as Array<keyof T>;

return keys.find(key => predicate(obj[key], key, obj));
}
1 change: 1 addition & 0 deletions src/object/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { clone } from './clone.ts';
export { cloneDeep } from './cloneDeep.ts';
export { findKey } from './findKey.ts';
export { flattenObject } from './flattenObject.ts';
export { invert } from './invert.ts';
export { mapKeys } from './mapKeys.ts';
Expand Down
Loading