-
Notifications
You must be signed in to change notification settings - Fork 1k
/
object.ts
34 lines (33 loc) · 940 Bytes
/
object.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Pick a list of properties from an object
* into a new object
*/
export const pick = <T extends object, TKeys extends keyof T>(obj: T, keys: TKeys[]): Pick<T, TKeys> => {
if (!obj) return {} as Pick<T, TKeys>;
return keys.reduce(
(acc, key) => {
if (Object.prototype.hasOwnProperty.call(obj, key)) acc[key] = obj[key];
return acc;
},
{} as Pick<T, TKeys>
);
};
/**
* Removes (shakes out) undefined entries from an
* object. Optional second argument shakes out values
* by custom evaluation.
*/
export const shake = <RemovedKeys extends string, T = object>(
obj: T,
filter: (value: unknown) => boolean = (x) => x === undefined || x === null
): Omit<T, RemovedKeys> => {
if (!obj) return {} as T;
const keys = Object.keys(obj) as (keyof T)[];
return keys.reduce((acc, key) => {
if (filter(obj[key])) {
return acc;
}
acc[key] = obj[key];
return acc;
}, {} as T);
};