assocPath.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import _curry3 from "./internal/_curry3.js";
  2. import _has from "./internal/_has.js";
  3. import _isInteger from "./internal/_isInteger.js";
  4. import _assoc from "./internal/_assoc.js";
  5. import isNil from "./isNil.js";
  6. /**
  7. * Makes a shallow clone of an object, setting or overriding the nodes required
  8. * to create the given path, and placing the specific value at the tail end of
  9. * that path. Note that this copies and flattens prototype properties onto the
  10. * new object as well. All non-primitive properties are copied by reference.
  11. *
  12. * @func
  13. * @memberOf R
  14. * @since v0.8.0
  15. * @category Object
  16. * @typedefn Idx = String | Int | Symbol
  17. * @sig [Idx] -> a -> {a} -> {a}
  18. * @param {Array} path the path to set
  19. * @param {*} val The new value
  20. * @param {Object} obj The object to clone
  21. * @return {Object} A new object equivalent to the original except along the specified path.
  22. * @see R.dissocPath
  23. * @example
  24. *
  25. * R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}}
  26. *
  27. * // Any missing or non-object keys in path will be overridden
  28. * R.assocPath(['a', 'b', 'c'], 42, {a: 5}); //=> {a: {b: {c: 42}}}
  29. */
  30. var assocPath =
  31. /*#__PURE__*/
  32. _curry3(function assocPath(path, val, obj) {
  33. if (path.length === 0) {
  34. return val;
  35. }
  36. var idx = path[0];
  37. if (path.length > 1) {
  38. var nextObj = !isNil(obj) && _has(idx, obj) && typeof obj[idx] === 'object' ? obj[idx] : _isInteger(path[1]) ? [] : {};
  39. val = assocPath(Array.prototype.slice.call(path, 1), val, nextObj);
  40. }
  41. return _assoc(idx, val, obj);
  42. });
  43. export default assocPath;