2e336c0dffcfb4b2d3a6ea90cd005f8312ae7557b221c620c911158052da933edeb28466204fcb7a811d47a689bbaafbf6bb53d81ae7b20894d14f9a9df406 986 B

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