object.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { pipe } from "fp-ts/function"
  2. import cloneDeep from "lodash/cloneDeep"
  3. import isEqual from "lodash/isEqual"
  4. import { JSPrimitive, TypeFromPrimitive } from "./primtive"
  5. export const objRemoveKey =
  6. <T, K extends keyof T>(key: K) =>
  7. (obj: T): Omit<T, K> =>
  8. pipe(cloneDeep(obj), (e) => {
  9. delete e[key]
  10. return e
  11. })
  12. export const objFieldMatches =
  13. <T, K extends keyof T, V extends T[K]>(
  14. fieldName: K,
  15. matches: ReadonlyArray<V>
  16. ) =>
  17. // eslint-disable-next-line no-unused-vars
  18. (obj: T): obj is T & { [_ in K]: V } =>
  19. matches.findIndex((x) => isEqual(obj[fieldName], x)) !== -1
  20. export const objHasProperty =
  21. <O extends object, K extends string, P extends JSPrimitive | undefined>(
  22. prop: K,
  23. type?: P
  24. ) =>
  25. // eslint-disable-next-line
  26. (obj: O): obj is O & { [_ in K]: TypeFromPrimitive<P> } =>
  27. // eslint-disable-next-line
  28. prop in obj && (type === undefined || typeof (obj as any)[prop] === type)
  29. type TypeFromPrimitiveArray<P extends JSPrimitive | undefined> =
  30. P extends "undefined"
  31. ? undefined
  32. : P extends "object"
  33. ? object[] | null
  34. : P extends "boolean"
  35. ? boolean[]
  36. : P extends "number"
  37. ? number[]
  38. : P extends "bigint"
  39. ? BigInt[]
  40. : P extends "string"
  41. ? string[]
  42. : P extends "symbol"
  43. ? Symbol[]
  44. : P extends "function"
  45. ? Function[]
  46. : unknown[]
  47. export const objHasArrayProperty =
  48. <O extends object, K extends string, P extends JSPrimitive>(
  49. prop: K,
  50. type: P
  51. ) =>
  52. // eslint-disable-next-line
  53. (obj: O): obj is O & { [_ in K]: TypeFromPrimitiveArray<P> } =>
  54. prop in obj &&
  55. Array.isArray((obj as any)[prop]) &&
  56. (obj as any)[prop].every(
  57. (val: unknown) => typeof val === type // eslint-disable-line
  58. )