You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.7 KiB

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