dissocPath.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import _curry2 from "./internal/_curry2.js";
  2. import _dissoc from "./internal/_dissoc.js";
  3. import _isInteger from "./internal/_isInteger.js";
  4. import _isArray from "./internal/_isArray.js";
  5. import assoc from "./assoc.js";
  6. /**
  7. * Makes a shallow clone of an object. Note that this copies and flattens
  8. * prototype properties onto the new object as well. All non-primitive
  9. * properties are copied by reference.
  10. *
  11. * @private
  12. * @param {String|Integer} prop The prop operating
  13. * @param {Object|Array} obj The object to clone
  14. * @return {Object|Array} A new object equivalent to the original.
  15. */
  16. function _shallowCloneObject(prop, obj) {
  17. if (_isInteger(prop) && _isArray(obj)) {
  18. return [].concat(obj);
  19. }
  20. var result = {};
  21. for (var p in obj) {
  22. result[p] = obj[p];
  23. }
  24. return result;
  25. }
  26. /**
  27. * Makes a shallow clone of an object, omitting the property at the given path.
  28. * Note that this copies and flattens prototype properties onto the new object
  29. * as well. All non-primitive properties are copied by reference.
  30. *
  31. * @func
  32. * @memberOf R
  33. * @since v0.11.0
  34. * @category Object
  35. * @typedefn Idx = String | Int | Symbol
  36. * @sig [Idx] -> {k: v} -> {k: v}
  37. * @param {Array} path The path to the value to omit
  38. * @param {Object} obj The object to clone
  39. * @return {Object} A new object without the property at path
  40. * @see R.assocPath
  41. * @example
  42. *
  43. * R.dissocPath(['a', 'b', 'c'], {a: {b: {c: 42}}}); //=> {a: {b: {}}}
  44. */
  45. var dissocPath =
  46. /*#__PURE__*/
  47. _curry2(function dissocPath(path, obj) {
  48. if (obj == null) {
  49. return obj;
  50. }
  51. switch (path.length) {
  52. case 0:
  53. return obj;
  54. case 1:
  55. return _dissoc(path[0], obj);
  56. default:
  57. var head = path[0];
  58. var tail = Array.prototype.slice.call(path, 1);
  59. if (obj[head] == null) {
  60. return _shallowCloneObject(head, obj);
  61. } else {
  62. return assoc(head, dissocPath(tail, obj[head]), obj);
  63. }
  64. }
  65. });
  66. export default dissocPath;