index.cjs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. 'use strict';
  2. function get(obj, path) {
  3. if (obj == null)
  4. return void 0;
  5. let value = obj;
  6. for (let i = 0; i < path.length; i++) {
  7. if (value == null || value[path[i]] == null)
  8. return void 0;
  9. value = value[path[i]];
  10. }
  11. return value;
  12. }
  13. function set(obj, value, path) {
  14. if (path.length === 0)
  15. return value;
  16. const idx = path[0];
  17. if (path.length > 1) {
  18. value = set(
  19. typeof obj !== "object" || obj === null || !Object.prototype.hasOwnProperty.call(obj, idx) ? Number.isInteger(Number(path[1])) ? [] : {} : obj[idx],
  20. value,
  21. Array.prototype.slice.call(path, 1)
  22. );
  23. }
  24. if (Number.isInteger(Number(idx)) && Array.isArray(obj))
  25. return obj.slice()[idx];
  26. return Object.assign({}, obj, { [idx]: value });
  27. }
  28. function unset(obj, path) {
  29. if (obj == null || path.length === 0)
  30. return obj;
  31. if (path.length === 1) {
  32. if (obj == null)
  33. return obj;
  34. if (Number.isInteger(path[0]) && Array.isArray(obj))
  35. return Array.prototype.slice.call(obj, 0).splice(path[0], 1);
  36. const result = {};
  37. for (const p in obj)
  38. result[p] = obj[p];
  39. delete result[path[0]];
  40. return result;
  41. }
  42. if (obj[path[0]] == null) {
  43. if (Number.isInteger(path[0]) && Array.isArray(obj))
  44. return Array.prototype.concat.call([], obj);
  45. const result = {};
  46. for (const p in obj)
  47. result[p] = obj[p];
  48. return result;
  49. }
  50. return set(
  51. obj,
  52. unset(
  53. obj[path[0]],
  54. Array.prototype.slice.call(path, 1)
  55. ),
  56. [path[0]]
  57. );
  58. }
  59. function deepPickUnsafe(obj, paths) {
  60. return paths.map((p) => p.split(".")).map((p) => [p, get(obj, p)]).filter((t) => t[1] !== void 0).reduce((acc, cur) => set(acc, cur[1], cur[0]), {});
  61. }
  62. function deepPick(obj, paths) {
  63. return deepPickUnsafe(obj, paths);
  64. }
  65. function deepOmitUnsafe(obj, paths) {
  66. return paths.map((p) => p.split(".")).reduce((acc, cur) => unset(acc, cur), obj);
  67. }
  68. function deepOmit(obj, paths) {
  69. return deepOmitUnsafe(obj, paths);
  70. }
  71. exports.deepOmit = deepOmit;
  72. exports.deepOmitUnsafe = deepOmitUnsafe;
  73. exports.deepPick = deepPick;
  74. exports.deepPickUnsafe = deepPickUnsafe;