UNPKG

util-ex

Version:

Browser-friendly enhanced util fully compatible with standard node.js

48 lines (47 loc) 2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.cloneObject = cloneObject; exports.default = void 0; var _getPrototypeOf = _interopRequireDefault(require("inherits-ex/lib/getPrototypeOf")); var _createObject = _interopRequireDefault(require("inherits-ex/lib/createObject")); var _clonePropertiesTo = _interopRequireDefault(require("./clone-properties-to.js")); var _function = _interopRequireDefault(require("./is/type/function.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Clones an object. * * @param {object} aObject - The object to be cloned. * @param {boolean|function} [tryCloneFn=true] - A boolean indicating whether or not to try to clone the object using a '`clone`' function, or a function that can be used to clone the object. If set to `false`, the object will not be cloned using the '`clone`' function, even if it exists. * @returns {object} The cloned object. * * @example * // Clone a simple object. * const myObject = { foo: 'bar' }; * const clonedObject = cloneObject(myObject); * * @example * // Clone an object using a custom clone function. * const myObject = { foo: 'bar', clone: function() { return { foo: this.foo }; } }; * const clonedObject = cloneObject(myObject); * * @example * // Clone an object without trying to use a custom clone function. * const myObject = { foo: 'bar', clone: function() { return { foo: this.foo }; } }; * const clonedObject = cloneObject(myObject, false); */ function cloneObject(aObject, tryCloneFn) { let result; if (tryCloneFn !== false && (0, _function.default)(aObject.clone)) { result = aObject.clone(); } else { const proto = (0, _getPrototypeOf.default)(aObject); const ctor = proto.hasOwnProperty('Class') ? proto.Class : aObject.constructor; result = (0, _createObject.default)(ctor); (0, _clonePropertiesTo.default)(result, aObject); } return result; } ; var _default = exports.default = cloneObject;