Created
December 18, 2020 11:06
-
-
Save JonCatmull/621113b24191197812c5dbe81c263935 to your computer and use it in GitHub Desktop.
Limit the amount of recursively nested child arrays on an object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Takes menu structure limits the number of levels of nesting. | |
* @param menuItems | |
* @param maxLevels | |
* @param level | |
*/ | |
export const truncateNesting = <T extends { children?: T[] }>( | |
menuItems: T[], | |
maxLevels: number, | |
level = 1 | |
): T[] => { | |
return menuItems.map((item) => { | |
if ("children" in item && item.children?.length) { | |
if (level >= maxLevels) { | |
const { children, ...itemWithoutChildren } = item; | |
return itemWithoutChildren as T; | |
} | |
const children = truncateNesting(item.children, maxLevels, level + 1); | |
return { ...item, children }; | |
} | |
return item; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment