phaser3-rex-plugins
Version:
58 lines (51 loc) • 2 kB
JavaScript
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
// Source object
// The key as a string, or an array of keys, i.e. 'banner', or 'banner.hideBanner'
// The default value to use if the key doesn't exist
/**
* Retrieves a value from an object.
*
* @function Phaser.Utils.Objects.GetValue
* @since 3.0.0
*
* @param {object} source - The object to retrieve the value from.
* @param {string} key - The name of the property to retrieve from the object. If a property is nested, the names of its preceding properties should be separated by a dot (`.`) - `banner.hideBanner` would return the value of the `hideBanner` property from the object stored in the `banner` property of the `source` object.
* @param {*} defaultValue - The value to return if the `key` isn't found in the `source` object.
*
* @return {*} The value of the requested key.
*/
var GetValue = function (source, key, defaultValue) {
if (!source || typeof source === 'number') {
return defaultValue;
}
else if (source.hasOwnProperty(key)) {
return source[key];
}
else if (key.indexOf('.') !== -1) {
var keys = key.split('.');
var parent = source;
var value = defaultValue;
// Use for loop here so we can break early
for (var i = 0; i < keys.length; i++) {
if (parent.hasOwnProperty(keys[i])) {
// Yes it has a key property, let's carry on down
value = parent[keys[i]];
parent = parent[keys[i]];
}
else {
// Can't go any further, so reset to default
value = defaultValue;
break;
}
}
return value;
}
else {
return defaultValue;
}
};
export default GetValue;