Skip to content

Instantly share code, notes, and snippets.

@legomolina
Last active October 1, 2024 22:28
Show Gist options
  • Save legomolina/5338c33e8ad2ef6622443e5e9aad4540 to your computer and use it in GitHub Desktop.
Save legomolina/5338c33e8ad2ef6622443e5e9aad4540 to your computer and use it in GitHub Desktop.
Alten technical challenge
const categories = [
{
name: 'category1',
subcategories: [
{
name: 'category2',
subcategories: []
},
{
name: 'category3',
subcategories: [
{
name: 'category4',
subcategories: []
}
]
}
]
},
{
name: 'category5',
subcategories: []
}
];
// Parse and store all possible routes to prevent tree traversing every time that `getCategoryPath` is called
const parsedCategories = [];
const traverseCategory = (categoryLevel, rootPath = '') => {
const currentPath = `${rootPath}/${categoryLevel.name}`;
if (categoryLevel.subcategories?.length > 0) {
categoryLevel.subcategories.forEach((subcategory) => {
traverseCategory(subcategory, currentPath);
});
}
parsedCategories.push(currentPath);
};
categories.forEach((category) => {
traverseCategory(category);
});
// At this time `parsedCategories` contains these values
/*
"/category1/category2"
"/category1/category3/category4"
"/category1/category3"
"/category1"
"/category5"
*/
// This function just needs to get the path from `parsedCategories`, a much simpler operation than finding it in the tree every time.
const getCategoryPath = (categories, categoryName) => {
const path = parsedCategories.find((path) => path.endsWith(categoryName));
return path ?? undefined;
};
// OUTPUT SAMPLES
console.log(getCategoryPath(categories, 'category4')); // should output: '/category1/category3/category4'
console.log(getCategoryPath(categories, 'category2')); // should output: '/category1/category2'
console.log(getCategoryPath(categories, 'category5')); // should output: '/category5'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment