Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(collections): ensure pick doesn't generate missing properties as undefined #5926

Merged
merged 6 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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