u
This commit is contained in:
@@ -132,3 +132,48 @@ export function getCategoryDescendantIds(categories, categoryId) {
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a category slug path by stripping leading/trailing slashes.
|
||||
* @param {string|null|undefined} slugPath
|
||||
* @returns {string}
|
||||
*/
|
||||
export function cleanCategorySlugPath(slugPath) {
|
||||
return (slugPath ?? '').replace(/^\/+|\/+$/g, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a numeric/string category ID from a URL slug path using the category tree.
|
||||
* @param {object} categories - id -> node map
|
||||
* @param {number|string|null} rootCategoryId
|
||||
* @param {string|null|undefined} slugPath
|
||||
* @returns {number|string|null}
|
||||
*/
|
||||
export function resolveCategoryIdFromSlugPath(categories, rootCategoryId, slugPath) {
|
||||
if (!categories || rootCategoryId == null) return null;
|
||||
|
||||
let segments = (slugPath ?? '')
|
||||
.split('/')
|
||||
.filter(Boolean)
|
||||
.map((segment) => decodeURIComponent(segment));
|
||||
|
||||
if (segments[0] === ROOT_CATEGORY_NAME) {
|
||||
segments = segments.slice(1);
|
||||
}
|
||||
|
||||
if (segments.length === 0) {
|
||||
return rootCategoryId;
|
||||
}
|
||||
|
||||
let currentId = rootCategoryId;
|
||||
for (const slug of segments) {
|
||||
const children = getCategoryChildren(categories, currentId);
|
||||
const match = children.find(
|
||||
(child) => categorySlug(child, rootCategoryId) === slug,
|
||||
);
|
||||
if (!match) return null;
|
||||
currentId = match.id;
|
||||
}
|
||||
|
||||
return currentId;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user