Dev Helpers
← Back

Count nodes recursively

Count nodes recursively 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 size(t: Tree): number {
      return 1 + t.children.reduce((n, c) => n + size(c), 0);
    }
    return size(root);
  })(),
);

Sample output

4