All files _cloneObject.js

62.5% Statements 70/112
50% Branches 48/96
80% Functions 12/15
63.3% Lines 69/109

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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264          2x 19x     19x         19x 19x     2x   2x       1x     2x       2x   1x 1x 1x 1x 1x       1x     2x       2x   1x     1x   1x 3x       3x         3x               3x 3x 1x 1x   2x       1x     5x     5x 7x   7x 3x     4x         4x                 4x 4x 1x 1x   3x         5x       2x                   12x   12x 12x 12x                   6x 1x     5x       5x 5x 5x 5x   5x                 1x 4x     3x         5x                           4x       4x 1x   4x 4x 8x 8x 7x     4x                                                                                                                  
import tools from './tools';
 
// Thanks for sharing code: http://jsfiddle.net/cattail/NYNT5/
 
// classify object
const classof = function classof(o) {
  Iif (o === null) {
    return 'null';
  }
  Iif (o === undefined) {
    return 'undefined';
  }
  // I suppose Object.prototype.toString use obj.constructor.name
  // to generate string
  const className = Object.prototype.toString.call(o).slice(8, -1);
  return className;
};
 
let references = null;
 
const handlers = {
  // Handle regexp and date even in shallow.
  RegExp: (function(_RegExp) {
    function RegExp(_x) {
      return _RegExp.apply(this, arguments);
    }
 
    RegExp.toString = function() {
      return _RegExp.toString();
    };
 
    return RegExp;
  })(reg => {
    let flags = '';
    flags += reg.global ? 'g' : '';
    flags += reg.multiline ? 'm' : '';
    flags += reg.ignoreCase ? 'i' : '';
    return new RegExp(reg.source, flags);
  }),
  Date: (function(_Date) {
    function Date(_x2) {
      return _Date.apply(this, arguments);
    }
 
    Date.toString = function() {
      return _Date.toString();
    };
 
    return Date;
  })(date => {
    return new Date(+date);
  }),
  Array: function Array(arr, shallow, filterFunc, cloneFunc) {
    const newArr = [];
    let i;
    for (i = 0; i < arr.length; i++) {
      Iif (shallow) {
        newArr[i] = arr[i];
      } else {
        // handle circular reference
        Iif (references.indexOf(arr[i]) !== -1) {
          continue;
        }
 
        // try to use clone function to copy value
        Iif (cloneFunc && arr[i]) {
          const clonedObject = cloneFunc(arr[i]);
          if (clonedObject) {
            newArr[i] = clonedObject;
            continue;
          }
        }
 
        const handler = handlers[classof(arr[i])];
        if (handler) {
          references.push(arr[i]);
          newArr[i] = handler(arr[i], false);
        } else {
          newArr[i] = arr[i];
        }
      }
    }
    return newArr;
  },
  Object: function Object(obj, shallow, filterFunc, cloneFunc) {
    const newObj = {};
    let prop;
    let handler;
    for (prop in obj) {
      Eif (obj.hasOwnProperty(prop)) {
        // escape prototype properties
        if (shallow || (filterFunc && !filterFunc(prop))) {
          newObj[prop] = obj[prop];
        } else {
          // handle circular reference
          Iif (references.indexOf(obj[prop]) !== -1) {
            continue;
          }
 
          // try to use clone function to copy value
          Iif (cloneFunc && obj[prop]) {
            const clonedObject = cloneFunc(obj[prop], prop);
            if (clonedObject) {
              newObj[prop] = clonedObject;
              continue;
            }
          }
 
          // recursive
          handler = handlers[classof(obj[prop])];
          if (handler) {
            references.push(obj[prop]);
            newObj[prop] = handler(obj[prop], false, filterFunc, cloneFunc);
          } else {
            newObj[prop] = obj[prop];
          }
        }
      }
    }
    return newObj;
  }
};
 
const _OBJECT = {
  /**
   * 克隆对象
   * @param {Object} obj js对象
   * @param {Boolean} shallow 是否进行浅层克隆, 如果是 false 则会完全进行克隆处理
   * @return {Object}
   */
  cloneObject(obj, shallow, filterFunc, cloneFunc) {
    // Thanks for sharing code: http://jsfiddle.net/cattail/NYNT5/
    // reset references
    references = [];
    // default to shallow clone
    shallow = shallow === undefined ? true : false;
    const handler = handlers[classof(obj)];
    return handler ? handler(obj, shallow, filterFunc, cloneFunc) : obj;
  },
  /**
   * 合并简单对象
   * @param {object} target 目标结构体
   * @param {object} source 源结构体
   * @param {boolean} overwrite 是否更新已经存在的属性
   * @return {object}
   */
  mergeObject(target, source, overwrite) {
    if (!source) {
      return _OBJECT.cloneObject(target);
    }
 
    Iif (!tools.isObject(source) || !tools.isObject(target)) {
      return overwrite ? _OBJECT.cloneObject(source) : target;
    }
 
    for (let key in source) {
      Eif (source.hasOwnProperty(key)) {
        const targetProp = target[key];
        const sourceProp = source[key];
 
        if (
          tools.isObject(sourceProp) &&
          tools.isObject(targetProp) &&
          !tools.isArray(sourceProp) &&
          !tools.isArray(targetProp) &&
          !tools.isDom(sourceProp) &&
          !tools.isDom(targetProp)
        ) {
          // 如果需要递归覆盖,就递归调用merge
          _OBJECT.mergeObject(targetProp, sourceProp, overwrite);
        } else if (overwrite || !(key in target)) {
          // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
          // NOTE,在 target[key] 不存在的时候也是直接覆盖
          target[key] = _OBJECT.cloneObject(source[key], true);
        }
      }
    }
 
    return target;
  },
 
  /**
   * 从指定object上获取目标 key 组成的对象。
   * 当 target 中不含目标key中的属性时,将不进行填充
   * null、''、0 将会被填充
   * @param {Object} target
   * @param {String|String[]} key
   * @example
   *  targetKeyObj({}, ['a', 'b', 'c']); // {}
   *  targetKeyObj({a: null}, ['a', 'b', 'c']); // {a: null}
   */
  targetKeyObj(target, key){
    Iif (tools.isEmpty(key)){
      return target;
    }
 
    if (!tools.isArray(key)){
      key = [key];
    }
    const result = {};
    for (let i = 0; i < key.length; i++) {
      const k = key[i];
      if (!tools.isUndefined(target[k])){
        result[k] = target[k];
      }
    }
    return result;
  },
 
  /**
   * 合并 JSON 数据
   * @param {*} oldJson
   * @param {*} targetKey 如:images、textures,shapes,skeletons,animations 等
   * @param {*} targetJson
   * @param {Boolean} repeatable 是否可重复
   */
  mergeObjJsonArray(oldJson, targetKey, targetJson, repeatable = true){
    const targetData = targetJson[targetKey];
 
    if (!tools.isEmpty(targetData)){
      if (!oldJson || !oldJson[targetKey]){
        oldJson[targetKey] = [];
      }
 
      if (repeatable){
        // 用于标识 targetKey 所对应的所有 uuids,主要用于判断重复
        if (!oldJson || !oldJson[`${targetKey}_uuids`]){
          oldJson[`${targetKey}_uuids`] = [];
        }
 
        const uuids = oldJson[`${targetKey}_uuids`];
 
        if (tools.isArray(targetData)){
          for (let i = 0, len = targetData.length; i < len; i++) {
            const item = targetData[i];
            if (!uuids.includes(item.uuid)){
              oldJson[targetKey].push(item);
              oldJson[`${targetKey}_uuids`].push(item.uuid);
            }
          }
        } else if (tools.isObject(targetData)){
          if (!uuids.includes(targetData.uuid)){
            oldJson[targetKey].push(targetData);
            oldJson[`${targetKey}_uuids`].push(targetData.uuid);
          }
        }
      } else {
        if (tools.isArray(targetData)){
          oldJson[targetKey].push(...targetData);
        } else if (tools.isObject(targetData)){
          oldJson[targetKey].push(targetData);
        }
      }
 
 
      // 拷贝完毕之后,清除目标元素的指定key
      delete targetJson[targetKey];
    }
 
  }
};
 
export default _OBJECT;