Dev Helpers
← Back

Return a path to a matching node

Return a path to a matching node 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(
  (() => {
    function walk(t: Tree, key: string): string[] | undefined {
      if (t.label === key) return [key];
      for (const c of t.children) {
        const p = walk(c, key);
        if (p) return [t.label, ...p];
      }
    }
    return walk(root, "ui");
  })(),
);

Sample output

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