UNPKG

pig-dam-core

Version:

Library that should be included in every Pig DAM project we build

89 lines (88 loc) 2.78 kB
"use strict"; /** * Date: 2019-07-09 * Time: 21:45 * @license MIT (see project's LICENSE file) */ Object.defineProperty(exports, "__esModule", { value: true }); exports.sort = exports.scrub = exports.ensure = exports.deletePath = exports.clone = void 0; const _ = require("lodash"); const mutable = require("../mutable/object"); /** * Clones an object or object path * @param object * @param path - It minimized the amount of data that needs to be cloned * @param {boolean} deep * @returns {Object} */ function clone(object, { deep = false, path } = {}) { if (path == null || path.length === 0) { return (deep) ? _.cloneDeep(object) : Object.assign({}, object); } else { const parts = path.split("."); object = _.clone(object); object[parts[0]] = clone(object[parts[0]], { deep, path: parts.slice(1).join() }); return object; } } exports.clone = clone; /** * Deletes the object at the property path in `object` * @param {Object|Array|null} object * @param {string} path * @returns {Object|Array} */ function deletePath(object, path) { return mutable.deletePath(_.cloneDeep(object), path); } exports.deletePath = deletePath; /** * A variation of lodash's set but only sets if the value is not set: * - if object is not set then it defaults to {} * - it returns the value at "path" */ function ensure(object, path, value) { return mutable.ensure(_.cloneDeep(object), path, value); } exports.ensure = ensure; /** * Removes properties of objects with <param>removables</param>values. It does not remove <param>removables</param> from arrays * but it does recursively process array elements and should they be objects then it will scrub those objects. * Note: must be careful to make sure there are no recursive references inside your object. * @param object will only process object passing isObject test * @param recursive whether to recurse into children properties * @param removables object or array of objects that qualify as or test for `remove` */ function scrub(object, { recursive = true, removables = [undefined] } = {}) { return mutable.scrub(_.cloneDeep(object), { recursive, removables }); } exports.scrub = scrub; /** * Recursively sorts object's properties */ function sort(object) { if (object != null) { if (_.isPlainObject(object)) { return Object.keys(object) .sort() .reduce((result, key) => { result[key] = sort(object[key]); return result; }, {}); } else if (_.isArray(object)) { return object.map(sort); } } return object; } exports.sort = sort;