UNPKG

1.33 kBJavaScriptView Raw
1var assignValue = require('./_assignValue'),
2 castPath = require('./_castPath'),
3 isIndex = require('./_isIndex'),
4 isKey = require('./_isKey'),
5 isObject = require('./isObject'),
6 toKey = require('./_toKey');
7
8/**
9 * The base implementation of `_.set`.
10 *
11 * @private
12 * @param {Object} object The object to modify.
13 * @param {Array|string} path The path of the property to set.
14 * @param {*} value The value to set.
15 * @param {Function} [customizer] The function to customize path creation.
16 * @returns {Object} Returns `object`.
17 */
18function baseSet(object, path, value, customizer) {
19 if (!isObject(object)) {
20 return object;
21 }
22 path = isKey(path, object) ? [path] : castPath(path);
23
24 var index = -1,
25 length = path.length,
26 lastIndex = length - 1,
27 nested = object;
28
29 while (nested != null && ++index < length) {
30 var key = toKey(path[index]),
31 newValue = value;
32
33 if (index != lastIndex) {
34 var objValue = nested[key];
35 newValue = customizer ? customizer(objValue, key, nested) : undefined;
36 if (newValue === undefined) {
37 newValue = isObject(objValue)
38 ? objValue
39 : (isIndex(path[index + 1]) ? [] : {});
40 }
41 }
42 assignValue(nested, key, newValue);
43 nested = nested[key];
44 }
45 return object;
46}
47
48module.exports = baseSet;