Initial commit
[yaffs-website] / node_modules / grunt-contrib-watch / node_modules / lodash / object / set.js
1 var isIndex = require('../internal/isIndex'),
2     isKey = require('../internal/isKey'),
3     isObject = require('../lang/isObject'),
4     toPath = require('../internal/toPath');
5
6 /**
7  * Sets the property value of `path` on `object`. If a portion of `path`
8  * does not exist it's created.
9  *
10  * @static
11  * @memberOf _
12  * @category Object
13  * @param {Object} object The object to augment.
14  * @param {Array|string} path The path of the property to set.
15  * @param {*} value The value to set.
16  * @returns {Object} Returns `object`.
17  * @example
18  *
19  * var object = { 'a': [{ 'b': { 'c': 3 } }] };
20  *
21  * _.set(object, 'a[0].b.c', 4);
22  * console.log(object.a[0].b.c);
23  * // => 4
24  *
25  * _.set(object, 'x[0].y.z', 5);
26  * console.log(object.x[0].y.z);
27  * // => 5
28  */
29 function set(object, path, value) {
30   if (object == null) {
31     return object;
32   }
33   var pathKey = (path + '');
34   path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path);
35
36   var index = -1,
37       length = path.length,
38       lastIndex = length - 1,
39       nested = object;
40
41   while (nested != null && ++index < length) {
42     var key = path[index];
43     if (isObject(nested)) {
44       if (index == lastIndex) {
45         nested[key] = value;
46       } else if (nested[key] == null) {
47         nested[key] = isIndex(path[index + 1]) ? [] : {};
48       }
49     }
50     nested = nested[key];
51   }
52   return object;
53 }
54
55 module.exports = set;