|
| 1 | +/** |
| 2 | + * @author Richard Davey <rich@photonstorm.com> |
| 3 | + * @copyright 2019 Photon Storm Ltd. |
| 4 | + * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} |
| 5 | + */ |
| 6 | + |
| 7 | +/** |
| 8 | + * Sets a value in an object, allowing for dot notation to control the depth of the property. |
| 9 | + * |
| 10 | + * For example: |
| 11 | + * |
| 12 | + * ```javascript |
| 13 | + * var data = { |
| 14 | + * world: { |
| 15 | + * position: { |
| 16 | + * x: 200, |
| 17 | + * y: 100 |
| 18 | + * } |
| 19 | + * } |
| 20 | + * }; |
| 21 | + * |
| 22 | + * SetValue(data, 'world.position.y', 300); |
| 23 | + * |
| 24 | + * console.log(data.world.position.y); // 300 |
| 25 | + * ``` |
| 26 | + * |
| 27 | + * @function Phaser.Utils.Objects.SetValue |
| 28 | + * @since 3.17.0 |
| 29 | + * |
| 30 | + * @param {object} source - The object to set the value in. |
| 31 | + * @param {string} key - The name of the property in the object. If a property is nested, the names of its preceding properties should be separated by a dot (`.`) |
| 32 | + * @param {any} value - The value to set into the property, if found in the source object. |
| 33 | + * |
| 34 | + * @return {boolean} `true` if the property key was valid and the value was set, otherwise `false`. |
| 35 | + */ |
| 36 | +var SetValue = function (source, key, value) |
| 37 | +{ |
| 38 | + if (!source || typeof source === 'number') |
| 39 | + { |
| 40 | + return false; |
| 41 | + } |
| 42 | + else if (source.hasOwnProperty(key)) |
| 43 | + { |
| 44 | + source[key] = value; |
| 45 | + |
| 46 | + return true; |
| 47 | + } |
| 48 | + else if (key.indexOf('.') !== -1) |
| 49 | + { |
| 50 | + var keys = key.split('.'); |
| 51 | + var parent = source; |
| 52 | + var prev = source; |
| 53 | + |
| 54 | + // Use for loop here so we can break early |
| 55 | + for (var i = 0; i < keys.length; i++) |
| 56 | + { |
| 57 | + if (parent.hasOwnProperty(keys[i])) |
| 58 | + { |
| 59 | + // Yes it has a key property, let's carry on down |
| 60 | + prev = parent; |
| 61 | + parent = parent[keys[i]]; |
| 62 | + } |
| 63 | + else |
| 64 | + { |
| 65 | + return false; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + prev[keys[keys.length - 1]] = value; |
| 70 | + |
| 71 | + return true; |
| 72 | + } |
| 73 | + |
| 74 | + return false; |
| 75 | +}; |
| 76 | + |
| 77 | +module.exports = SetValue; |
0 commit comments