Skip to content

Commit

Permalink
fix(collections): ensure pick doesn't generate missing properties a…
Browse files Browse the repository at this point in the history
…s `undefined` (#5926)
  • Loading branch information
yuhr committed Sep 12, 2024
1 parent 7d3dd2d commit 1a3a515
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
4 changes: 3 additions & 1 deletion collections/pick.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,7 @@ export function pick<T extends object, K extends keyof T>(
obj: Readonly<T>,
keys: readonly K[],
): Pick<T, K> {
return Object.fromEntries(keys.map((k) => [k, obj[k]])) as Pick<T, K>;
const result = {} as Pick<T, K>;
for (const key of keys) if (key in obj) result[key] = obj[key];
return result;
}
13 changes: 13 additions & 0 deletions collections/pick_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ Deno.test({
},
});

Deno.test({
name:
"pick() returns a new object without properties missing in the original object",
fn() {
// deno-lint-ignore no-explicit-any
const obj = { a: 5, b: 6, c: 7, d: 8 } as any;
const picked: { a: 5; x?: 5; y?: 5 } = pick(obj, ["a", "x", "y"]);

assertEquals(picked, { a: 5 });
assertNotStrictEquals(picked, obj);
},
});

Deno.test({
name:
"pick() returns a new object from the provided object with the provided keys",
Expand Down

0 comments on commit 1a3a515

Please sign in to comment.