(function () { 'use strict'; var tool = {}; /** * Returns type of variable in original case * @param {*} mixed * @param {Boolean} [lowerCase] * @return {String} */ tool.getType = function (mixed, lowerCase) { var type = (null === mixed || undefined === mixed) ? '' + mixed : Object.prototype.toString.call(mixed).slice(8, -1); return (lowerCase) ? type.toLowerCase() : type; }; /** * Return true if mixed is empty: undefined, null, '', 0, NaN, [], {}; if deep - if all properties are empty * @param {*} mixed * @param {Boolean} [deep] * @return {Boolean} */ tool.isEmpty = function (mixed, deep) { var name, type = typeof mixed; if ('function' === type) { return false; } if (!mixed || 0 === mixed.length) { return true; } if ('object' !== type) { return false; } for (name in mixed) { if (deep) { if (mixed.hasOwnProperty(name)) { if (!tool.isEmpty(mixed[name], deep)) { return false; } } } else { if (mixed.hasOwnProperty(name)) { return false; } } } return true; }; /** * Get property specified by complex name from Object or Array * @param {Object|Array} source Source data * @param {String} field Parts of complex names should be separated with dot * @param {*} [defaultValue] * @return {*|undefined} */ tool.get = function (source, field, defaultValue) { var data = source; var path = ('' + field).split('.'); for (var i = 0, count = path.length; i < count && null != data; ++i) { data = data[path[i]]; } return (undefined === data) ? defaultValue : data; }; /** * Set property specified by complex name in Object or Array * @param {Object|Array} target * @param {String|Array} fields Parts of complex names should be separated with dot * @param {*} value * @return {Boolean} */ tool.set = function (target, fields, value) { var data, path, k, kc, i, ic; var isObject = function (obj) { var type = Object.toString.call(obj); return ('[object Object]' === type || '[object Array]' === type); }; if (isObject(target)) { data = target; fields = 'Array' === tool.getType(fields) ? fields : [fields]; for (k = 0, kc = fields.length; k < kc; ++k) { path = ('' + fields[k]).split('.'); for (i = 0, ic = path.length - 1; i < ic; ++i) { if ('undefined' === typeof data[path[i]]) { data[path[i]] = {}; } if (isObject(data[path[i]])) { data = data[path[i]]; } else { return false; } } data[path[path.length - 1]] = value; } return true; } return false; }; angular.module('tool', []).value('tool', tool); })();