From dc7b2cceba591b47ba79bcfd6b8c4a3321de267b Mon Sep 17 00:00:00 2001 From: Matteo Sacchetto <56300116+matteosacchetto@users.noreply.github.com> Date: Fri, 21 Oct 2022 01:17:52 +0200 Subject: [PATCH] fix: address pick issue when key not in object (#112) * 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 (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) --- package.json | 2 +- src/object.ts | 6 ++++-- src/tests/object.test.ts | 12 ++++++++++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index e902a3a8..8411d9d5 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/object.ts b/src/object.ts index db3e7dc7..023cd105 100644 --- a/src/object.ts +++ b/src/object.ts @@ -150,13 +150,15 @@ export const listify = ( * Pick a list of properties from an object * into a new object */ -export const pick = ( +export const pick = , TKeys extends keyof T>( obj: T, keys: TKeys[] ): Pick => { if (!obj) return {} as Pick return keys.reduce((acc, key) => { - return { ...acc, [key]: obj[key] } + if(obj.hasOwnProperty(key)) + acc[key] = obj[key] + return acc; }, {} as Pick) } diff --git a/src/tests/object.test.ts b/src/tests/object.test.ts index ae1081fb..a40a14cb 100644 --- a/src/tests/object.test.ts +++ b/src/tests/object.test.ts @@ -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, {