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: add matchKeys function #27

Merged
merged 7 commits into from
Jun 26, 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
39 changes: 39 additions & 0 deletions docs/curry/matchKeys.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
title: matchKeys
group: 'Curry'
description: Create a key-matching function
---

## Basic usage

You have a utility function that is filtering an object's properties somehow. Using `matchKeys` will allow your function to filter those properties based on either an array of keys (an allowlist) or a function that returns a boolean for each property.

```ts
import { matchKeys, KeyFilter } from 'radash'

// Define your function with a `KeyFilter` parameter type,
// then use `matchKeys` to create a function that will
// filter the object's properties for you.
function filterObjectSomeway(obj: object, keys: KeyFilter) {
const matches = matchKeys(keys)
for (const key in obj) {
const value = obj[key]
if (matches(value, key, obj)) {
// ...
}
}
}
```

In the next example, the `obj` whose properties are being filtered is passed into `matchKeys` to simplify the signature of the returned function. Notice how we call `matches(key)` instead of the `matches(value, key, obj)` from the previous example. Both ways have their trade-offs, but this way is the one you'll probably use most often.

```ts
function filterObjectSomehow(obj: object, keys: KeyFilter) {
const matches = matchKeys(keys, obj)
for (const key in obj) {
if (matches(key)) {
// ...
}
}
}
```
43 changes: 43 additions & 0 deletions src/curry/matchKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { isArray } from 'radashi'

type KeyOf<T extends object> = object extends T ? keyof any : keyof T
type ValueOf<T extends object> = object extends T ? unknown : T[keyof T]

export type KeyMatcher<T extends object = object> = (
value: ValueOf<T>,
key: KeyOf<T>,
obj: T
) => boolean

/**
* Functions can use this type to accept either an array of keys or a
* filter callback. This provides type safety for such a parameter
* type, whose value can then be passed into `matchKeys` to receive a
* matching function.
*/
export type KeyFilter<
T extends object = object,
Key extends KeyOf<T> = KeyOf<T>
> = KeyMatcher<T> | readonly Key[]

/**
* Wrap an array of keys with a “key matcher” function that returns
* true if a given key-value pair is both in the array and an
* enumerable property in the given object.
*
* If you pass in a function, it will be returned as is. The function
* should have a `(value, key, obj) => boolean` signature.
*/
export const matchKeys: {
<T extends object>(keys: KeyFilter<T>): KeyMatcher
<T extends object>(keys: KeyFilter<T>, obj: T): (key: keyof any) => boolean
} = (keys: KeyFilter, obj?: object): any => {
const matcher: KeyMatcher = isArray(keys)
? (_, key, obj) =>
Object.hasOwnProperty.call(obj, key) && keys.includes(key)
: keys

return obj
? (key: keyof any) => matcher((obj as any)[key], key, obj)
: matcher
}
49 changes: 49 additions & 0 deletions src/curry/tests/matchKeys.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import * as _ from 'radashi'

describe('matchKeys function', () => {
const objectEntries = Object.entries as <T extends object>(
obj: T
) => [keyof T, T[keyof T]][]

test('accepts an array of keys', () => {
const keys = ['a', 'b']
const matches = _.matchKeys(keys)
const obj = {
a: 1,
b: 2,
c: 3
}
for (const [key, value] of objectEntries(obj)) {
expect(matches(value, key, obj)).toBe(keys.includes(key))
}
})
test('accepts a filter callback', () => {
const matches = _.matchKeys(
(value, key) => value !== undefined || key === 'd'
)
const obj = {
a: 1,
b: undefined,
c: 3,
d: undefined
}
for (const [key, value] of objectEntries(obj)) {
expect(matches(value, key, obj)).toBe(value !== undefined || key === 'd')
}
})
test('does not match non-enumerable keys', () => {
const matches = _.matchKeys(['a', 'b'])
class A {
a = 1
b() {}
}
const a = new A()
expect(matches(a.a, 'a', a)).toBe(true)
expect(matches(a.b, 'b', a)).toBe(false)
})
test('accepts an object as 2nd argument', () => {
const matches = _.matchKeys(['a'], { a: 1, b: 2 })
expect(matches('a')).toBe(true)
expect(matches('b')).toBe(false)
})
})
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export * from './curry/callable'
export * from './curry/chain'
export * from './curry/compose'
export * from './curry/debounce'
export * from './curry/matchKeys'
export * from './curry/memo'
export * from './curry/partial'
export * from './curry/partob'
Expand Down