js 拷贝树copytree

希望能摆脱lodash的深拷贝 🐻

const l = console.log;
/**
 *
 * @param tree 需要克隆的对象
 * @param all  是否需要克隆不可枚举属性
 */
export function copytree(tree: any, all: boolean = true) {
  const objectTag = "[object Object]";
  const arrayTag = "[object Array]";

  const _tostring = (value: any): string =>
    Object.prototype.toString.call(value);
  // 记录所有的对象
  const map = new WeakMap();
  function copyTree(tree: any, all: boolean = true) {
    const treeTag = _tostring(tree);
    const res: any =
      treeTag === objectTag ? {} : treeTag === arrayTag ? [] : tree;

    if (treeTag !== objectTag && treeTag !== arrayTag) return res;

    // 判断是否有此对象
    if (map.has(tree)) {
      // 直接返回
      return tree;
    } else {
      map.set(tree, true);
    }

    const t = all ? Object.getOwnPropertyNames(tree) : tree;

    if (all) {
      for (const i in t) {
        const k = t[i];
        res[k] = copyTree(tree[k], all);
      }
    } else {
      for (const k in t) {
        res[k] = copyTree(tree[k], all);
      }
    }

    return res;
  }

  return copyTree(tree, all);
}

let b: any = {
  name: "ajanuw",
  age: 12,
  obj: {
    name: "a"
  }
};

b.obj.b = b;

let x = copytree(b);

l(x);
l(b);
posted @ 2018-06-02 00:58  Ajanuw  阅读(575)  评论(0编辑  收藏  举报