Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
traverses a tree data structure and prints the contents in the specified format - javascript, typescript

recently I have one task that says: traverses a tree data structure and print the content in the specified format I have tried till now but I can't achieve what I want.

const data = {
  name: "my-project",
  children: [
 {
  name: "node_modules",
  children: [
    {
      name: "react",
      children: [
        { name: "docs", children: [] },
       
      ],
    },
  ],
},
{ name: "src", children: [{ name: "index.js" }] },
]};


// my-project
// ├── node_modules
// │   └── react
// │       ├── docs
// └── src
//     └── index.js

I am trying to solve like this but any help would be good.

let position = 0;

function start(tree) {
if (!tree) {
 return
}
let current = tree;

if(position === 0) {
 console.log('// ' + current.name);
} else {
 console.log(`// ${'     '.repeat(position)}|___${current.name}`);
}

while(current) {
 current = current.children.shift();
 position++;
 start(current);
}
}

start(data);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

How's this?

const data = {
  name: "my-project",
  children: [
 {
  name: "node_modules",
  children: [
    {
      name: "react",
      children: [
        { name: "docs", children: [] },
       
      ],
    },
  ],
},
{ name: "src", children: [{ name: "index.js" }] },
]};

const prettyPrint = (tree, depth) => {
    if(depth === 0) {
   console.log('// ' + tree.name);
  } else if (depth === 1) {
   console.log(`// |${'────'.repeat(depth)} ${tree.name}`);
  } else {
   console.log(`// |${'    '.repeat(depth - 1)} |──── ${tree.name}`);
  }
  
  if(tree.children){
    tree.children.forEach(curr => prettyPrint(curr, depth + 1));
  }
}

prettyPrint(data, 0)

JSFiddle: https://jsfiddle.net/7qoyg8ep/

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda