phaser
Version:
A fast, free and fun HTML5 Game Framework for Desktop and Mobile web browsers.
66 lines (59 loc) • 2.04 kB
JavaScript
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|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;
}
};
module.exports = GetValue;