@onesy/utils
Version:
42 lines (41 loc) • 1.8 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const is_1 = __importDefault(require("./is"));
const copy_1 = __importDefault(require("./copy"));
const optionsDefault = {
copy: false,
merge: {
array: false,
},
};
const merge = (target, source, options_ = {}) => {
const options = Object.assign(Object.assign({}, optionsDefault), options_);
if (options.merge.array &&
(0, is_1.default)('array', target) && (0, is_1.default)('array', source)) {
const length = Math.max(target.length, source.length);
for (let i = 0; i < length; i++) {
if (target[i] === undefined)
target[i] = source[i];
if (((0, is_1.default)('object', target[i]) && (0, is_1.default)('object', source[i])) ||
(0, is_1.default)('array', target[i]) && (0, is_1.default)('array', source[i]))
target[i] = merge(target[i], source[i], options);
}
}
if ((0, is_1.default)('object', target) && (0, is_1.default)('object', source)) {
Object.keys(source).forEach(key => {
// We only care about direct target object properties
// not about inherited properties from a prototype chain
if (target.hasOwnProperty(key)) {
if ((0, is_1.default)('object', target[key]) && (0, is_1.default)('object', source[key]))
target[key] = merge(target[key], source[key], options);
}
else
target[key] = options.copy ? (0, copy_1.default)(source[key]) : source[key];
});
}
return target;
};
exports.default = merge;
;