copy-tree.js 770 B

123456789101112131415161718192021222324252627282930
  1. 'use strict'
  2. var createNode = require('./node.js').create
  3. module.exports = function (tree) {
  4. return copyTree(tree, {})
  5. }
  6. function copyTree (tree, cache) {
  7. if (cache[tree.path]) { return cache[tree.path] }
  8. var newTree = cache[tree.path] = createNode(Object.assign({}, tree))
  9. copyModuleList(newTree, 'children', cache)
  10. newTree.children.forEach(function (child) {
  11. child.parent = newTree
  12. })
  13. copyModuleList(newTree, 'requires', cache)
  14. copyModuleList(newTree, 'requiredBy', cache)
  15. return newTree
  16. }
  17. function copyModuleList (tree, key, cache) {
  18. var newList = []
  19. if (tree[key]) {
  20. tree[key].forEach(function (child) {
  21. const copy = copyTree(child, cache)
  22. if (copy) {
  23. newList.push(copy)
  24. }
  25. })
  26. }
  27. tree[key] = newList
  28. }