Dev Helpers
← Back

Visit nodes breadth first

Visit nodes breadth first using TypeScript.

Open this example in the interactive library

Source code

type Tree = { label: string; children: Tree[] };
const root: Tree = {
  label: "src",
  children: [
    { label: "app", children: [{ label: "ui", children: [] }] },
    { label: "lib", children: [] },
  ],
};
console.log(
  (() => {
    const queue: Tree[] = [root],
      out: string[] = [];
    for (const t of queue) {
      out.push(t.label);
      queue.push(...t.children);
    }
    return out;
  })(),
);

Sample output

[ 'src', 'app', 'lib', 'ui' ]