1 import { INavItem } from "../../components/layout/nav-item"
2
3 /**
4 * Sort menu items by rank in ascending order.
5 * Items with rank come first, sorted by rank value.
6 * Items without rank come last, maintaining their original order.
7 * Recursively sorts nested items independently.
8 */
9 export function sortMenuItemsByRank(
10 items: (INavItem & { rank?: number })[]
11 ): INavItem[] {
12 // Sort items by rank (ascending order)
13 // Items with rank come first, sorted by rank value
14 // Items without rank come last, maintaining their original order
15 const sortedItems = items.sort((a, b) => {
16 // If both have rank, sort by rank value
17 if (a.rank !== undefined && b.rank !== undefined) {
18 return a.rank - b.rank
19 }
20 // If only a has rank, it comes first
21 if (a.rank !== undefined) {
22 return -1
23 }
24 // If only b has rank, it comes first
25 if (b.rank !== undefined) {
26 return 1
27 }
28 // If neither has rank, maintain original order
29 return 0
30 })
31
32 // Recursively sort nested items
33 sortedItems.forEach((item) => {
34 if (item.items && item.items.length > 0) {
35 item.items = sortMenuItemsByRank(
36 item.items as (INavItem & { rank?: number })[]
37 )
38 }
39 })
40
41 return sortedItems
42 }