import {groupBy} from './collections'

// group crumbs that share a place; crumbs without a place are skipped.
// generic so callers keep their own crumb type (e.g. a located narrowing)

export type PlaceGroup<T> = {
  placeId: string
  crumbs: T[]
}

export const groupByPlace = <T extends {place: {id: string} | null}>(
  crumbs: T[],
): PlaceGroup<T>[] =>
  [
    ...groupBy(
      crumbs.filter((c) => c.place),
      (c) => c.place!.id,
      (c) => c,
    ),
  ].map(([placeId, crumbs]) => ({placeId, crumbs}))
