Skip to content

Commit

Permalink
add object-key-by-value
Browse files Browse the repository at this point in the history
  • Loading branch information
yano3nora committed Jul 1, 2023
1 parent ef14251 commit b9f45a2
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ objectByKeys([1, 2, 3], (key) => Number(key) * 10)

# Development
```sh
$ code src/new-function.ts # add function
$ code src/new-function.test.ts # add test
$ code main.ts # add export

$ deno task dev
```

Expand Down
1 change: 1 addition & 0 deletions main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export * from './src/is-number.ts'
export * from './src/nameof.ts'
export * from './src/object-by-keys.ts'
export * from './src/object-keys.ts'
export * from './src/object-key-by-value.ts'
export * from './src/objects-2-object.ts'
export * from './src/object-swap.ts'
export * from './src/percent-weighted-avg.ts'
Expand Down
22 changes: 22 additions & 0 deletions src/object-key-by-value.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { assertEquals } from 'https://deno.land/std@0.186.0/testing/asserts.ts'
import { objectKeyByValue } from './object-key-by-value.ts'

Deno.test('object-key-by-value', async test => {
await test.step('case of undefined', () => {
const obj = { one: 1 }

assertEquals(
objectKeyByValue(obj, 2),
undefined,
)
})

await test.step('case of exists', () => {
const obj = { one: 1 }

assertEquals(
objectKeyByValue(obj, 1),
'one',
)
})
})
13 changes: 13 additions & 0 deletions src/object-key-by-value.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { objectKeys } from './object-keys.ts'

/**
* @example
* const obj = { one: 1 }
* const key = objectKeyByValue(obj, 1) // 'one' | undefined
*/
export const objectKeyByValue = <
T extends Record<PropertyKey, U>,
U = unknown
>(object: T, value: U) => {
return objectKeys(object).find(key => object[key] === value)
}

0 comments on commit b9f45a2

Please sign in to comment.