const buildTree = (headings) => {
  const roots = [];
  const stack = [];
  headings.forEach((heading) => {
    const item = {
      ...heading,
      children: []
    };
    while (stack.length > 0 && stack[stack.length - 1].level >= heading.level) {
      stack.pop();
    }
    const parent = stack[stack.length - 1];
    if (parent) {
      parent.children.push(item);
    } else {
      roots.push(item);
    }
    stack.push(item);
  });
  return roots;
};
const alphabeticalIndexCollator = (() => {
  try {
    return new Intl.Collator(void 0, { sensitivity: "base", numeric: true });
  } catch {
    return { compare: (a, b) => a.localeCompare(b) };
  }
})();
const getAlphabeticalIndexLetter = (text) => {
  const firstCharacter = text.trim().charAt(0).toUpperCase();
  return /^[A-Z]$/.test(firstCharacter) ? firstCharacter : "#";
};
const buildAlphabeticalGroups = (headings) => {
  const sortedHeadings = [...headings].sort((left, right) => {
    const textComparison = alphabeticalIndexCollator.compare(left.text, right.text);
    if (textComparison !== 0) {
      return textComparison;
    }
    return alphabeticalIndexCollator.compare(left.nodeId, right.nodeId);
  });
  return sortedHeadings.reduce((groups, heading) => {
    const letter = getAlphabeticalIndexLetter(heading.text);
    const existingGroup = groups[groups.length - 1];
    if (!existingGroup || existingGroup.letter !== letter) {
      groups.push({
        letter,
        items: [heading]
      });
      return groups;
    }
    existingGroup.items.push(heading);
    return groups;
  }, []);
};
export {
  buildAlphabeticalGroups,
  buildTree
};
//# sourceMappingURL=tree-builder.js.map
