Path: blob/master/node_modules/@hapi/hoek/lib/merge.js
1126 views
'use strict';12const Assert = require('./assert');3const Clone = require('./clone');4const Utils = require('./utils');567const internals = {};8910module.exports = internals.merge = function (target, source, options) {1112Assert(target && typeof target === 'object', 'Invalid target value: must be an object');13Assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');1415if (!source) {16return target;17}1819options = Object.assign({ nullOverride: true, mergeArrays: true }, options);2021if (Array.isArray(source)) {22Assert(Array.isArray(target), 'Cannot merge array onto an object');23if (!options.mergeArrays) {24target.length = 0; // Must not change target assignment25}2627for (let i = 0; i < source.length; ++i) {28target.push(Clone(source[i], { symbols: options.symbols }));29}3031return target;32}3334const keys = Utils.keys(source, options);35for (let i = 0; i < keys.length; ++i) {36const key = keys[i];37if (key === '__proto__' ||38!Object.prototype.propertyIsEnumerable.call(source, key)) {3940continue;41}4243const value = source[key];44if (value &&45typeof value === 'object') {4647if (target[key] === value) {48continue; // Can occur for shallow merges49}5051if (!target[key] ||52typeof target[key] !== 'object' ||53(Array.isArray(target[key]) !== Array.isArray(value)) ||54value instanceof Date ||55(Buffer && Buffer.isBuffer(value)) || // $lab:coverage:ignore$56value instanceof RegExp) {5758target[key] = Clone(value, { symbols: options.symbols });59}60else {61internals.merge(target[key], value, options);62}63}64else {65if (value !== null &&66value !== undefined) { // Explicit to preserve empty strings6768target[key] = value;69}70else if (options.nullOverride) {71target[key] = value;72}73}74}7576return target;77};787980