diff --git a/packages/stdlib/src/objects/pick/index.test.ts b/packages/stdlib/src/objects/pick/index.test.ts new file mode 100644 index 0000000..48c088f --- /dev/null +++ b/packages/stdlib/src/objects/pick/index.test.ts @@ -0,0 +1,36 @@ +import { describe, it, expect } from 'vitest'; +import { pick } from '.'; + +describe('pick', () => { + it('pick a single key', () => { + const result = pick({ a: 1, b: 2, c: 3 }, 'a'); + + expect(result).toEqual({ a: 1 }); + }); + + it('pick multiple keys', () => { + const result = pick({ a: 1, b: 2, c: 3 }, ['a', 'b']); + + expect(result).toEqual({ a: 1, b: 2 }); + }); + + it('return an empty object when no keys are provided', () => { + const result = pick({ a: 1, b: 2 }, []); + + expect(result).toEqual({}); + }); + + it('handle non-existent keys by setting them to undefined', () => { + const result = pick({ a: 1, b: 2 }, ['a', 'c'] as any); + + expect(result).toEqual({ a: 1, c: undefined }); + }); + + it('return an empty object if target is null or undefined', () => { + const emptyTarget = pick(null as any, 'a'); + const emptyKeys = pick({ a: 1 }, null as any); + + expect(emptyTarget).toEqual({}); + expect(emptyKeys).toEqual({}); + }); +}); \ No newline at end of file diff --git a/packages/stdlib/src/objects/pick/index.ts b/packages/stdlib/src/objects/pick/index.ts new file mode 100644 index 0000000..9a0b167 --- /dev/null +++ b/packages/stdlib/src/objects/pick/index.ts @@ -0,0 +1,38 @@ +import { isArray, type Arrayable } from '../../types'; + +/** + * @name pick + * @category Objects + * @description Returns a partial copy of an object containing only the keys specified + * + * @param {object} target - The object to pick keys from + * @param {Arrayable} keys - The keys to pick + * @returns {Pick} The new object with the specified keys picked + * + * @example + * pick({ a: 1, b: 2, c: 3 }, 'a') // => { a: 1 } + * + * @example + * pick({ a: 1, b: 2, c: 3 }, ['a', 'b']) // => { a: 1, b: 2 } + * + * @since 0.0.3 + */ +export function pick( + target: Target, + keys: Arrayable +): Pick { + const result = {} as Pick; + + if (!target || !keys) + return result; + + if (isArray(keys)) { + for (const key of keys) { + result[key] = target[key]; + } + } else { + result[keys] = target[keys]; + } + + return result; +} \ No newline at end of file