modifyPath.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import _curry3 from "./internal/_curry3.js";
  2. import _isArray from "./internal/_isArray.js";
  3. import _isObject from "./internal/_isObject.js";
  4. import _has from "./internal/_has.js";
  5. import _assoc from "./internal/_assoc.js";
  6. import _modify from "./internal/_modify.js";
  7. /**
  8. * Creates a shallow clone of the passed object by applying an `fn` function
  9. * to the value at the given path.
  10. *
  11. * The function will not be invoked, and the object will not change
  12. * if its corresponding path does not exist in the object.
  13. * All non-primitive properties are copied to the new object by reference.
  14. *
  15. * @func
  16. * @memberOf R
  17. * @since v0.28.0
  18. * @category Object
  19. * @sig [Idx] -> (v -> v) -> {k: v} -> {k: v}
  20. * @param {Array} path The path to be modified.
  21. * @param {Function} fn The function to apply to the path.
  22. * @param {Object} object The object to be transformed.
  23. * @return {Object} The transformed object.
  24. * @example
  25. *
  26. * const person = {name: 'James', address: { zipCode: '90216' }};
  27. * R.modifyPath(['address', 'zipCode'], R.reverse, person); //=> {name: 'James', address: { zipCode: '61209' }}
  28. *
  29. * // Can handle arrays too
  30. * const person = {name: 'James', addresses: [{ zipCode: '90216' }]};
  31. * R.modifyPath(['addresses', 0, 'zipCode'], R.reverse, person); //=> {name: 'James', addresses: [{ zipCode: '61209' }]}
  32. */
  33. var modifyPath =
  34. /*#__PURE__*/
  35. _curry3(function modifyPath(path, fn, object) {
  36. if (!_isObject(object) && !_isArray(object) || path.length === 0) {
  37. return object;
  38. }
  39. var idx = path[0];
  40. if (!_has(idx, object)) {
  41. return object;
  42. }
  43. if (path.length === 1) {
  44. return _modify(idx, fn, object);
  45. }
  46. var val = modifyPath(Array.prototype.slice.call(path, 1), fn, object[idx]);
  47. if (val === object[idx]) {
  48. return object;
  49. }
  50. return _assoc(idx, val, object);
  51. });
  52. export default modifyPath;