Skip to content

Commit

Permalink
feat: add keyValue function
Browse files Browse the repository at this point in the history
  • Loading branch information
Arcath committed Mar 22, 2023
1 parent de4cc62 commit 79ad2b3
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
17 changes: 16 additions & 1 deletion src/functions/keys.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {keys} from '../'
import {keys, keyValue} from '../'

describe('Keys', () => {
it('should return an array of keys', () => {
Expand All @@ -12,4 +12,19 @@ describe('Keys', () => {

expect(k).toHaveLength(3)
})

it('should return keys and values', () => {
const sample = {
a: 1,
b: 'two',
c: true
}

const kv = keyValue(sample)

expect(kv).toHaveLength(3)

expect(kv[0].key).toBe('a')
expect(kv[0].value).toBe(1)
})
})
15 changes: 15 additions & 0 deletions src/functions/keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,18 @@ export const keys = <T extends {}>(object: T): (keyof T)[] => {
//eslint-disable-next-line
return objectKeys.filter(key => object.hasOwnProperty(key)) as any
}

type KeyValueArray<
Object extends {},
Key extends keyof Object = keyof Object
> = {key: Key; value: Object[Key]}[]

export const keyValue = <Object extends {}>(
object: Object
): KeyValueArray<Object> => {
const objectKeys = keys(object)

return objectKeys.map(key => {
return {key, value: object[key]}
})
}
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export {
export {indexedBy, IndexedArray, IndexedByOptions} from './functions/indexed-by'
export {invariant, InvariantOptions} from './functions/invariant'
export {isEnv, isProduction, isDev, isTest} from './functions/is-env'
export {keys} from './functions/keys'
export {keys, keyValue} from './functions/keys'
export {parseCDIR, CIDRObject} from './functions/network'
export {mapProperty} from './functions/map-property'
export {rangeAsString, rangeAsArray} from './functions/range-as-string'
Expand Down

0 comments on commit 79ad2b3

Please sign in to comment.