Задача про составление пути до файла

Задача про составление пути до файла. Есть дерево tree, нужно получить массив путей. Не понимаю как ее решить.

Мой вариант без рекурсии:

const tree = [
    'index.css',
    'test.css',
    {
        src: [
            'test.js',
            {
                components: [
                    'Component.jsx',
                    'Home.jsx'
                ]
            }
        ]
    }
]

function expandTree(tree) {
    let res = []
    let str = ''
    let isTree = true
    let curTree = tree
    while (isTree) {
        isTree = false
        for (let i = 0; i < curTree.length; i++) {
            if (typeof(curTree[i]) === "object") {
                let name = Object.keys(curTree[i])[0]
                curTree = curTree[i][name]
                str += name + "/"
                isTree = true
                break
            } else {
                res.push(str + curTree[i])
            }
        }
    }
    return res
}

console.log(expandTree(tree));


Ответы (1 шт):

Автор решения: Grundy

Так как узлы дерева должны обрабатываться однообразно можно воспользоваться рекурсивной функцией expandTree:

  1. перебираем все узлы
  2. если узел является строкой - добавляем его в результат
  3. если узел является объектом
    1. перебираем все пары "ключ-значение"
    2. для каждого значения снова вызываем функцию expandTree
    3. полученный массив добавляем в результат

Пример:

const tree = [
  'index.css',
  'test.css',
  {
    src: [
      'test.js',
      {
        components: [
          'Component.jsx',
          'Home.jsx'
        ]
      }
    ]
  }
]

function expandTree(tree, path = '') {
  let result = [];
  for (const item of tree) {
    if (typeof item == 'string') {
      result.push((path ? path + '/' : path) + item);
      continue;
    }
    for (const [subpath, subtree] of Object.entries(item)) {
      result.push(...expandTree(subtree, (path ? path + '/' : path) + subpath))
    }
    // result.push(...[].concat(...Object.entries(item).map(([subpath, subtree]) => expandTree(subtree, (path ? path + '/' : path) + subpath))));
  }
  return result;
}

console.log(expandTree(tree));

/* Что должно получиться
Output: [
 'index.css',
 'test.css',
 'src/test.js',
 'src/components/Component.jsx',
 'src/components/Home.jsx'
]
*/

→ Ссылка