Imagine I have a set of website routes represented by the object below:
const routes = {
HOME: "start",
ACCOUNT: {
HOME: "account",
PROFILE: "profile",
ADDRESSES: {
HOME: "addresses",
DETAIL: ":addressId",
},
},
ESHOP: {
HOME: "eshop",
INVOICES: "invoices",
ORDERS: {
HOME: "orders",
DETAIL: ":orderId",
},
},
INVENTORY: {
HOME: "warehouse",
CATEGORIES: {
HOME: "categories",
CATEGORY: {
HOME: ":categoryId",
PRODUCTS: {
HOME: "products",
PRODUCT: ":productId",
},
},
},
},
};
I am looking to create a concise and elegant function that can generate the full path from a given path consisting of known object keys, like so:
buildRoute(routes, "routes.ACCOUNT.ADDRESSES.DETAIL")
// should output: "start/account/addresses/:addressId"
or
buildRoute(routes, "routes.INVENTORY.CATEGORIES")
// should output: "start/warehouse/categories"
or
buildRoute(routes, "routes.INVENTORY.CATEGORIES.CATEGORY.PRODUCTS.PRODUCT")
// should output: "start/warehouse/categories/:categoryId/products/:productId"
In this case, "routes" represents the object containing the routes, "HOME" is the fixed key for each path/subpath, and a slash should be included between all subroutes except the last one. I plan to provide the data as strings rather than values when implementing this solution.
If you have any suggestions on how to achieve this with clean and concise code, particularly in TypeScript with defined types, it would be greatly appreciated!