|
1 | 1 | /**
|
2 | 2 | * Removes properties from an object, based on the values in an array, and returns the new object.
|
3 | 3 | * Equivalent to an object version of TS Omit<>
|
4 |
| - * |
5 |
| - * @param {Record<PropertyKey, unknown>} objToPluck |
6 |
| - * @param {ReadonlyArray<PropertyKey>} keysToPluck |
7 |
| - * @returns |
8 | 4 | */
|
9 |
| -export const omit = <A extends Record<PropertyKey, unknown>, B extends ReadonlyArray<PropertyKey>>( |
| 5 | +export const omit = < |
| 6 | + A extends Record<PropertyKey, unknown>, |
| 7 | + const B extends ReadonlyArray<PropertyKey> |
| 8 | +>( |
10 | 9 | objToPluck: A,
|
11 |
| - keysToPluck: B |
| 10 | + keysToPluck: B | (keyof A)[] |
12 | 11 | ): Omit<A, B[number]> =>
|
13 | 12 | Object.keys(objToPluck)
|
14 |
| - .filter((key) => !keysToPluck.includes(key)) |
| 13 | + .filter( |
| 14 | + (key) => !keysToPluck.map((el) => (typeof el === 'string' ? el : el.toString())).includes(key) |
| 15 | + ) |
15 | 16 | .reduce((result, key) => ({...result, [key]: objToPluck[key]}), {} as Omit<A, B[number]>)
|
| 17 | + |
| 18 | +/** |
| 19 | + * Picks properties from an object, base on the values in an array, and returns the new object. |
| 20 | + * Equivalent to an object version of TS Pick<> |
| 21 | + */ |
| 22 | +export const pick = < |
| 23 | + A extends Record<PropertyKey, unknown>, |
| 24 | + const B extends ReadonlyArray<PropertyKey> |
| 25 | +>( |
| 26 | + objToPluck: A, |
| 27 | + keysToPluck: B | (keyof A)[] |
| 28 | +): Pick<A, B[number]> => |
| 29 | + [...keysToPluck].reduce((memo, prop) => { |
| 30 | + memo[prop] = objToPluck[prop] |
| 31 | + return memo |
| 32 | + }, {} as Record<PropertyKey, unknown>) as Pick<A, B[number]> |
0 commit comments