Files
negareh-console/src/pages/request/utils/categoryUtils.ts
T
2026-07-21 11:16:33 +03:30

95 lines
2.4 KiB
TypeScript

import type { CategoryType } from '../type/Types'
export const extractList = <T,>(payload: unknown): T[] => {
if (Array.isArray(payload)) return payload
if (payload && typeof payload === 'object' && 'data' in payload) {
const maybeData = (payload as { data?: unknown }).data
return Array.isArray(maybeData) ? (maybeData as T[]) : []
}
return []
}
export const findCategoryById = (
categories: CategoryType[],
targetId: string,
): CategoryType | null => {
for (const category of categories) {
if (category.id === targetId) {
return category
}
if (category.children?.length) {
const found = findCategoryById(category.children, targetId)
if (found) return found
}
}
return null
}
export const findCategoryPath = (
categories: CategoryType[],
targetId: string,
): string[] | null => {
for (const category of categories) {
if (category.id === targetId) {
return [category.id]
}
if (category.children?.length) {
const childPath = findCategoryPath(category.children, targetId)
if (childPath) {
return [category.id, ...childPath]
}
}
}
return null
}
export const getCategoriesAtLevel = (
categories: CategoryType[],
level: number,
selectedPath: string[],
): CategoryType[] => {
if (level === 0) return categories
const parentId = selectedPath[level - 1]
if (!parentId) return []
const parent = findCategoryById(categories, parentId)
return parent?.children ?? []
}
export const getLevelsToShow = (
categories: CategoryType[],
selectedPath: string[],
): number[] => {
const levels = [0]
for (let level = 0; level < selectedPath.length; level++) {
const category = findCategoryById(categories, selectedPath[level])
if (category?.children?.length) {
levels.push(level + 1)
}
}
return levels
}
export const buildPathToFirstLeaf = (
categories: CategoryType[],
categoryId: string,
prefixPath: string[] = [],
): string[] => {
const path = [...prefixPath, categoryId]
let current = findCategoryById(categories, categoryId)
while (current?.children?.length) {
path.push(current.children[0].id)
current = current.children[0]
}
return path
}