UNPKG

jsm-utilities

Version:
49 lines (48 loc) 1.64 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generatePathWithParams = generatePathWithParams; exports.getJsmRouteTree = getJsmRouteTree; /** * Replaces `:param` tokens in a route template with values from `params`. * * @example * generatePath("/dash/centers/:id", { id: "123" }) // "/dash/centers/123" */ function generatePathWithParams(template, params) { return template.replace(/:([A-Za-z0-9_]+)/g, (_, key) => { if (!(key in params)) { throw new Error(`Missing route param: ${key}`); } // Always URI-encode to stay safe for special characters return encodeURIComponent(String(params[key])); }); } function getJsmRouteTree(MENU_ITEMS, childNode) { const findParents = (currentNode, path = []) => { const currentPath = [...path, currentNode]; if ((currentNode === null || currentNode === void 0 ? void 0 : currentNode.path) === childNode.path) { return currentPath; } if (currentNode === null || currentNode === void 0 ? void 0 : currentNode._) { for (const key in currentNode._) { const child = currentNode._[key]; const found = findParents(child, currentPath); if (found) { return found; } } } return null; }; const result = []; if (!childNode) return []; for (const key in MENU_ITEMS) { const found = findParents(MENU_ITEMS[key]); if (found) { result.push(found); } } return result[0] || []; } ;