Skip to content

Instantly share code, notes, and snippets.

@JonCatmull
Created December 18, 2020 11:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonCatmull/621113b24191197812c5dbe81c263935 to your computer and use it in GitHub Desktop.
Save JonCatmull/621113b24191197812c5dbe81c263935 to your computer and use it in GitHub Desktop.
Limit the amount of recursively nested child arrays on an object.
/**
* 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