All files / obj merge.js

100% Statements 27/27
100% Branches 16/16
100% Functions 8/8
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 692x         2x 231x           2x 112x 112x       3x 109x       3x   106x       2x 4x 7x       2x 120x 105x                                 2x 118x 117x 117x 119x 1x 118x 117x     117x     2x  
var $type = require('./type');
 
var mergeArr;
var mergeObj;
 
var isObj = function (item) {
  return (
    item
    && typeof item === 'object'
  );
};
 
var mergeItem = function (origin, item, key) {
  var prev = origin[key];
  if (
    $type(prev) === 'array'
    && $type(item) === 'array'
  ) {
    mergeArr(prev, item);
  } else if (
    isObj(prev)
    && isObj(item)
  ) {
    mergeObj(prev, item);
  } else {
    origin[key] = item;
  }
};
 
mergeArr = function (origin, source) {
  source.forEach(function (item, index) {
    mergeItem(origin, item, index);
  });
};
 
mergeObj = function (origin, source) {
  Object.keys(source).forEach(function (key) {
    mergeItem(origin, source[key], key);
  });
};
 
/**
 * 深度混合源对象,会保留函数引用
 * @method obj/merge
 * @param {Object} origin 要混合的源对象
 * @param {Object} target 要混合的对象
 * @returns {Object} 混合之后的对象
 * @example
 * var $merge = require('@spore-ui/kit/packages/obj/merge');
 * var origin = {a:{b:{c:1}}};
 * var target = {a:{b:{d:2}}};
 * console.info($merge(origin, target));
 * // {a:{b:{c:1,d:2}}};
 */
var merge = function (origin) {
  if (typeof origin !== 'object') return origin;
  var rests = Array.prototype.slice.call(arguments, 1);
  rests.forEach(function (source) {
    if ($type(source) === 'array') {
      mergeArr(origin, source);
    } else if (isObj(source)) {
      mergeObj(origin, source);
    }
  });
  return origin;
};
 
module.exports = merge;