|
| 1 | +import { DeepStrictObjectKeys } from '../types/DeepStrictObjectKeys'; |
| 2 | +import { DeepStrictPick } from '../types/DeepStrictPick'; |
| 3 | + |
| 4 | +/** |
| 5 | + * @title Runtime Function for Type-Safe Deep Property Picking. |
| 6 | + * |
| 7 | + * Takes an object and a dot-notation key path, and returns a new object |
| 8 | + * containing only the specified nested property, preserving the original structure. |
| 9 | + * |
| 10 | + * This is the runtime counterpart of the {@link DeepStrictPick} type. |
| 11 | + * |
| 12 | + * @template T - The object type of the input |
| 13 | + * @template K - The key path to pick |
| 14 | + * @param input - The source object to extract properties from |
| 15 | + * @param key - A dot-notation key path specifying which property to pick |
| 16 | + * @returns A new object containing only the picked property with its original structure |
| 17 | + * |
| 18 | + * @example |
| 19 | + * ```ts |
| 20 | + * const result = deepStrictPick({ a: { b: 1, c: 2 } }, 'a.b'); |
| 21 | + * // result: { a: { b: 1 } } |
| 22 | + * ``` |
| 23 | + */ |
| 24 | +export const deepStrictPick = <T extends object, K extends DeepStrictObjectKeys<T>>( |
| 25 | + input: T, |
| 26 | + key: K, |
| 27 | +): DeepStrictPick<T, K> => { |
| 28 | + const keys = key.split(/(?:\[\*\])?\./g).filter(Boolean); |
| 29 | + |
| 30 | + const traverse = (input: Record<string, any> | Record<string, any>[], keys: string[]): any => { |
| 31 | + const [first, ...rest] = keys; |
| 32 | + |
| 33 | + if (input instanceof Array) { |
| 34 | + const elements = input.map((element) => { |
| 35 | + if (first in element) { |
| 36 | + if (typeof element[first] === 'object' && element[first] !== null && rest.length > 0) { |
| 37 | + return { [first]: traverse(element[first], rest) }; |
| 38 | + } |
| 39 | + |
| 40 | + return { [first]: element[first] }; |
| 41 | + } |
| 42 | + |
| 43 | + return element; |
| 44 | + }); |
| 45 | + |
| 46 | + return elements; |
| 47 | + } else { |
| 48 | + if (first in input) { |
| 49 | + if (typeof input[first] === 'object' && input[first] !== null && rest.length > 0) { |
| 50 | + return { [first]: traverse(input[first], rest) }; |
| 51 | + } |
| 52 | + return { [first]: input[first] }; |
| 53 | + } |
| 54 | + |
| 55 | + throw new Error(`input doesn\'t has key: ${first}`); |
| 56 | + } |
| 57 | + }; |
| 58 | + |
| 59 | + return traverse(input, keys) as DeepStrictPick<T, K>; |
| 60 | +}; |
0 commit comments