All files / obj cloneDeep.js

100% Statements 19/19
100% Branches 4/4
100% Functions 5/5
100% Lines 19/19

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 462x                                 2x 6x 6x 13x   6x     2x 8x 8x 11x 11x   8x     2x 86x 6x   80x 8x   72x     2x  
var $type = require('./type');
 
/**
 * 深度克隆对象,会保留函数引用
 * @method obj/cloneDeep
 * @param {Object} item 要克隆的对象
 * @returns {Object} 克隆后的对象
 * @example
 * var $cloneDeep = require('@spore-ui/kit/packages/obj/cloneDeep');
 * var obj = {a: 1, b: 2, c: function () {}};
 * console.info($cloneDeep(obj)); //{a: 1, b: 2, c: function () {}}
 */
 
var cloneArr;
var cloneObj;
var cloneDeep;
 
cloneArr = function (arr) {
  var carr = [];
  arr.forEach(function (item, index) {
    carr[index] = cloneDeep(item);
  });
  return carr;
};
 
cloneObj = function (obj) {
  var cobj = {};
  Object.keys(obj).forEach(function (key) {
    var item = obj[key];
    cobj[key] = cloneDeep(item);
  });
  return cobj;
};
 
cloneDeep = function (item) {
  if ($type(item) === 'array') {
    return cloneArr(item);
  }
  if ($type(item) === 'object') {
    return cloneObj(item);
  }
  return item;
};
 
module.exports = cloneDeep;