flatten-tree.js 1021 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. 'use strict'
  2. var validate = require('aproba')
  3. var moduleName = require('../utils/module-name.js')
  4. module.exports = flattenTree
  5. module.exports.flatName = flatName
  6. module.exports.flatNameFromTree = flatNameFromTree
  7. function flattenTree (tree) {
  8. validate('O', arguments)
  9. var seen = new Set()
  10. var flat = {}
  11. var todo = [[tree, '/']]
  12. while (todo.length) {
  13. var next = todo.shift()
  14. var pkg = next[0]
  15. seen.add(pkg)
  16. var path = next[1]
  17. flat[path] = pkg
  18. if (path !== '/') path += '/'
  19. for (var ii = 0; ii < pkg.children.length; ++ii) {
  20. var child = pkg.children[ii]
  21. if (!seen.has(child)) {
  22. todo.push([child, flatName(path, child)])
  23. }
  24. }
  25. }
  26. return flat
  27. }
  28. function flatName (path, child) {
  29. validate('SO', arguments)
  30. return path + (moduleName(child) || 'TOP')
  31. }
  32. function flatNameFromTree (tree) {
  33. validate('O', arguments)
  34. if (tree.isTop) return '/'
  35. var path = flatNameFromTree(tree.parent)
  36. if (path !== '/') path += '/'
  37. return flatName(path, tree)
  38. }