export function orderByRequirementForGrouping<T>(
  items: readonly T[],
  requirementIds: readonly string[],
  getRequirementId: (item: T) => string | undefined,
): T[] {
  const rankByRequirement = new Map(requirementIds.map((id, index) => [id, index]));
  const trailingRank = requirementIds.length;

  return [...items]
    .map((item, index) => {
      const requirementId = getRequirementId(item);
      return {
        item,
        index,
        rank: requirementId ? (rankByRequirement.get(requirementId) ?? trailingRank) : trailingRank,
      };
    })
    .sort((a, b) => a.rank - b.rank || a.index - b.index)
    .map(({ item }) => item);
}
