From b865b582420b6ac940a4a54e83874011710081ab Mon Sep 17 00:00:00 2001 From: Philipp Burckhardt Date: Fri, 16 Jun 2023 11:22:21 -0400 Subject: [PATCH] feat: improve type safety of functions --- src/utils.ts | 45 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 37 insertions(+), 8 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 879432d..67285b0 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -138,18 +138,47 @@ export function stringifyForModel(json: types.Jsonifiable): string { } } -export function pick(obj: T, ...keys: string[]): U { - return Object.fromEntries( - keys.filter((key) => key in obj).map((key) => [key, obj[key]]) - ) as U +/** + * Picks keys from an object. + * + * @param obj - object to pick keys from + * @param keys - keys to pick from the object + * @returns new object with only the picked keys + */ +export function pick( + obj: T, + ...keys: K[] +) { + return keys.reduce((result, key) => { + result[key] = obj[key] + return result + }, {} as Pick) } -export function omit(obj: T, ...keys: string[]): U { - return Object.fromEntries( - Object.entries(obj).filter(([key]) => !keys.includes(key)) - ) as U +/** + * Omits keys from an object. + * + * @param obj - object to omit keys from + * @param keys - keys to omit from the object + * @returns new object without the omitted keys + */ +export function omit( + obj: T, + ...keys: K[] +) { + const keySet = new Set(keys) + return Object.keys(obj).reduce((result, key) => { + if (!keySet.has(key as K)) { + result[key] = obj[key as keyof T] + } + + return result + }, {} as Omit) } +/** + * Function that does nothing. + */ const noop = () => undefined /**