UNPKG

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