UNPKG

@selenite/commons

Version:

This typescript package provides a set of frequently used utilities, types and svelte actions for building projects with Typescript and Svelte.

48 lines (47 loc) 1.46 kB
export function isForest(candidate) { return candidate.forest !== undefined; } export function makeTree({ items, pathKey, sort }) { const collector = { leaves: [], forest: new Map() }; for (const item of items) { let current = collector; for (const parent of item[pathKey] ?? []) { if (!current.forest.has(parent)) { current.forest.set(parent, { leaves: [], forest: new Map() }); } current = current.forest.get(parent); } current.leaves.push(item); } // console.debug('collector', collector); const res = []; function rec(current, currentCollector) { current.push(...(sort ? currentCollector.leaves.toSorted(sort) : currentCollector.leaves)); const forestEntries = [...currentCollector.forest.entries()]; if (sort) { forestEntries.sort(([a], [b]) => a.localeCompare(b)); } for (const [k, v] of forestEntries) { const forest = []; current.push({ label: k, forest }); rec(forest, v); } } rec(res, collector); return res; } export function flattenTree(tree) { const res = []; function rec(current) { for (const item of current) { if (isForest(item)) { rec(item.forest); } else { res.push(item); } } } rec(tree); return res; }