import type { GridRowId } from '../types' import type { Collection } from './types' const getAllParents = ( parentLookup: Map, id: null | GridRowId ) => { const parentIds: GridRowId[] = [] if (id === null) { return parentIds } let parentId: null | GridRowId = parentLookup.get(id) ?? null while (parentId !== null) { parentIds.push(parentId) parentId = parentLookup.get(parentId) ?? null } return parentIds } export const buildParentLookup = (collection: Collection) => { const parentLookup = new Map() const collect = (nodeId: GridRowId, parentId: GridRowId | null) => { if (parentId) { parentLookup.set(nodeId, parentId) } const meta = collection.meta.get(nodeId) if (meta?.children?.length) { meta.children.forEach((childId) => collect(childId, nodeId)) } } collection.ids.forEach((id) => collect(id, null)) return { parentLookup, getAllParents(id: null | GridRowId) { return getAllParents(parentLookup, id) }, } }