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 1 commit
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);
});
});
31 changes: 31 additions & 0 deletions docs/ja/reference/object/findKey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# 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, K>(obj: Record<T, K>, predicate: (value: K, key: T, obj: Record<T, K>) => boolean): T | undefined;
```

### Parameters

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

### Returns

(`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
```
31 changes: 31 additions & 0 deletions docs/ko/reference/object/findKey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# findKey

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

## 인터페이스

```typescript
function findKey<T, K>(obj: Record<T, K>, predicate: (value: K, key: T, obj: Record<T, K>) => boolean): T | undefined;
```

### 파라미터

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

### 반환 값

(`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
```
31 changes: 31 additions & 0 deletions docs/reference/object/findKey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# findKey

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

## Signature

```typescript
function findKey<T, K>(obj: Record<T, K>, predicate: (value: K, key: T, obj: Record<T, K>) => boolean): T | undefined;
```

### Parameters

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

### Returns

(`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
```
31 changes: 31 additions & 0 deletions docs/zh_hans/reference/object/findKey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# findKey

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

## Signature

```typescript
function findKey<T, K>(obj: Record<T, K>, predicate: (value: K, key: T, obj: Record<T, K>) => boolean): T | undefined;
```

### Parameters

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

### Returns

(`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');
});
});
24 changes: 24 additions & 0 deletions src/object/findKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* 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 PropertyKey, K>(
obj: Record<T, K>,
predicate: (value: K, key: T, obj: Record<T, K>) => boolean
): T | undefined {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
export function findKey<T extends PropertyKey, K>(
obj: Record<T, K>,
predicate: (value: K, key: T, obj: Record<T, K>) => boolean
): T | undefined {
export function findKey<T extends Record<any, any>>(
obj: T,
predicate: (value: T[keyof T], key: keyof T, obj: T) => boolean
): keyof T | undefined {

I guess this type signature is more accurate than the original one.


Note that foo is inferred as number | string in the first one, but is accurately inferred as number in the second one.

Old interface

declare function findKey<T extends PropertyKey, K>(
  obj: Record<T, K>,
  predicate: (value: K, key: T, obj: Record<T, K>) => boolean
): T | undefined

findKey({ foo: 1, bar: '1' }, (val, key, obj) => {
  // foo is string | number here
  obj.foo
})
image

New interface

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

findKey({ foo: 1, bar: '1' }, (val, key, obj) => {
  // foo is number here
  obj.foo
})
image

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

Wow, thank you for the kind review.

In the case of the old interface, the type inference of the object's key and value is inferred independently, so accurate type inference is not possible.

I will commit again, reflecting your review!!

return (Object.keys(obj) as Array<T>).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
Expand Up @@ -11,3 +11,4 @@ export { omitBy } from './omitBy.ts';
export { pick } from './pick.ts';
export { pickBy } from './pickBy.ts';
export { toMerged } from './toMerged.ts';
export { findKey } from './findKey.ts';