mirror of
https://github.com/penxio/penx.git
synced 2026-01-13 15:38:12 -05:00
22 lines
726 B
TypeScript
22 lines
726 B
TypeScript
import { CatalogueNodeType } from '@penx/model-type'
|
|
import type { CatalogueNode } from './CatalogueNode'
|
|
import { WithFlattenProps } from './types'
|
|
|
|
export function flattenTree(
|
|
items: CatalogueNode[],
|
|
type?: CatalogueNodeType,
|
|
parentId: string | null = null,
|
|
depth = 0,
|
|
): WithFlattenProps<CatalogueNode>[] {
|
|
return items.reduce<WithFlattenProps<CatalogueNode>[]>((acc, item, index) => {
|
|
const flattenNode = Object.assign(item, { parentId, depth, index })
|
|
|
|
if (typeof type === 'undefined') acc.push(flattenNode)
|
|
if (type === item.type) acc.push(flattenNode)
|
|
if (item?.children?.length) {
|
|
acc.push(...flattenTree(item.children || [], type, item.id, depth + 1))
|
|
}
|
|
return acc
|
|
}, [])
|
|
}
|