childrenOf

tcmts.share.childrenOf · #r5qfkeqz · term · runs anywhere

The namespaces directly in one, and its definitions.

import type { NameRow } from "#codebase/tcmts/store";

export function childrenOf(
  rows: NameRow[],
  ns: string,
): { namespaces: { name: string; rows: NameRow[] }[]; defs: NameRow[] } {
  const prefix = ns ? `${ns}.` : "";
  const subs = new Map<string, NameRow[]>();
  const defs: NameRow[] = [];
  for (const r of rows) {
    if (!r.path.startsWith(prefix)) continue;
    const rest = r.path.slice(prefix.length);
    const dot = rest.indexOf(".");
    if (dot < 0) defs.push(r);
    else {
      const name = prefix + rest.slice(0, dot);
      if (!subs.has(name)) subs.set(name, []);
      subs.get(name)!.push(r);
    }
  }
  return {
    namespaces: [...subs]
      .map(([name, rows]) => ({ name, rows }))
      .sort((a, b) => b.rows.length - a.rows.length || (a.name < b.name ? -1 : 1)),
    defs: defs.sort((a, b) => (a.path < b.path ? -1 : 1)),
  };
}

uses

used by