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(pick): accept a callback for advanced picking #30

Merged
merged 4 commits into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
17 changes: 16 additions & 1 deletion docs/object/pick.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: pick
description: Pick only the desired attributes from an object
description: Pick only the desired properties from an object
---

## Basic usage
Expand All @@ -19,3 +19,18 @@ const fish = {

_.pick(fish, ['name', 'source']) // => { name, source }
```

### Predicate function

The `pick` function can also accept a predicate function as the filter argument. This allows for more complex filtering logic beyond simple key inclusion or exclusion.

```ts
import * as _ from 'radashi'

const source = { a: 1, b: 2, c: 3, d: 4 }

_.pick(source, (value, key) => {
return value % 2 === 0 // Include only even values
})
// => { b: 2, d: 4 }
```
36 changes: 23 additions & 13 deletions src/object/pick.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
import { type FilteredKeys, filterKey, isArray, type KeyFilter } from 'radashi'

/**
* Pick a list of properties from an object into a new object
*/
export function pick<T extends object, TKeys extends keyof T>(
export function pick<T extends object, F extends KeyFilter<T, keyof T>>(
obj: T,
keys: TKeys[],
): Pick<T, TKeys> {
filter: F,
): Pick<T, FilteredKeys<T, F>>

export function pick<T extends object>(
obj: T,
filter: KeyFilter<T, keyof T> | null,
) {
if (!obj) {
return {} as Pick<T, TKeys>
return {}
}
let keys: (keyof T)[] = filter as any
if (isArray(filter)) {
filter = null
} else {
keys = Reflect.ownKeys(obj) as (keyof T)[]
}
return keys.reduce(
(acc, key) => {
if (Object.hasOwnProperty.call(obj, key)) {
acc[key] = obj[key]
}
return acc
},
{} as Pick<T, TKeys>,
)
return keys.reduce((acc, key) => {
if (filterKey(obj, key, filter)) {
acc[key] = obj[key]
}
return acc
}, {} as T)
}
7 changes: 7 additions & 0 deletions tests/object/pick.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,11 @@ describe('pick', () => {
a: 2,
})
})
test('works with predicate function', () => {
const result = _.pick({ a: 1, b: 2, c: 3, d: 4 }, value => value % 2 === 0)
expect(result).toEqual({
b: 2,
d: 4,
})
})
})