Skip to content

Commit

Permalink
fix: address pick issue when key not in object (#112)
Browse files Browse the repository at this point in the history
* fix: address pick issue when key not in object

* fix: restrict T to a generic object and use .hasOwnProperty()

restrict the type of T to be Record<string, unknown> (thus, a generic object) and use the .hasOwnProperty() method to check if key is in obj

* test: add test for missing key and undefined property

* chore: bump version to 8.0.2 (patch)
  • Loading branch information
matteosacchetto authored Oct 20, 2022
1 parent 5a11fc5 commit dc7b2cc
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "radash",
"version": "8.0.1",
"version": "8.0.2",
"description": "Functional utility library - modern, simple, typed, powerful",
"main": "dist/cjs/index.cjs",
"module": "dist/esm/index.mjs",
Expand Down
6 changes: 4 additions & 2 deletions src/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,15 @@ export const listify = <TValue, TKey extends string | number | symbol, KResult>(
* Pick a list of properties from an object
* into a new object
*/
export const pick = <T, TKeys extends keyof T>(
export const pick = <T extends Record<string, unknown>, TKeys extends keyof T>(
obj: T,
keys: TKeys[]
): Pick<T, TKeys> => {
if (!obj) return {} as Pick<T, TKeys>
return keys.reduce((acc, key) => {
return { ...acc, [key]: obj[key] }
if(obj.hasOwnProperty(key))
acc[key] = obj[key]
return acc;
}, {} as Pick<T, TKeys>)
}

Expand Down
12 changes: 12 additions & 0 deletions src/tests/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,18 @@ describe('object module', () => {
const result = _.pick({ a: 2 }, [])
assert.deepEqual(result, {})
})
test('handle key not in object', () => {
const result = _.pick({ a: 2, b: 3 } as any, ['c'])
assert.deepEqual(result, {} as any)
})
test('handle one key not in object', () => {
const result = _.pick({ a: 2, b: 3 } as any, ['a', 'c'])
assert.deepEqual(result, { a: 2 } as any)
})
test('does not ignore undefined values', () => {
const result = _.pick({ a: 2, b: undefined }, ['b'])
assert.deepEqual(result, { b: undefined })
})
test('returns picked properties only', () => {
const result = _.pick({ a: 2, b: 4 }, ['a'])
assert.deepEqual(result, {
Expand Down

0 comments on commit dc7b2cc

Please sign in to comment.