| 1 |
const { isArray } = Array; |
| 2 |
const { getPrototypeOf, prototype: objectProto, keys: getKeys } = Object; |
| 3 |
|
| 4 |
/** |
| 5 |
* Used in functions where either a list of arguments, a single array of arguments, or a |
| 6 |
* dictionary of arguments can be returned. Returns an object with an `args` property with |
| 7 |
* the arguments in an array, if it is a dictionary, it will also return the `keys` in another |
| 8 |
* property. |
| 9 |
*/ |
| 10 |
export function argsArgArrayOrObject<T, O extends Record<string, T>>(args: T[] | [O] | [T[]]): { args: T[]; keys: string[] | null } { |
| 11 |
if (args.length === 1) { |
| 12 |
const first = args[0]; |
| 13 |
if (isArray(first)) { |
| 14 |
return { args: first, keys: null }; |
| 15 |
} |
| 16 |
if (isPOJO(first)) { |
| 17 |
const keys = getKeys(first); |
| 18 |
return { |
| 19 |
args: keys.map((key) => first[key]), |
| 20 |
keys, |
| 21 |
}; |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
return { args: args as T[], keys: null }; |
| 26 |
} |
| 27 |
|
| 28 |
function isPOJO(obj: any): obj is object { |
| 29 |
return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto; |
| 30 |
} |