Currently, I am facing a challenge in mapping objects with keys for easy retrieval. The issue arises when the key can either be a string or a RegExp. Assigning a string as a key is simple, but setting a regex as a key poses a problem.
This is how I typically set a key for an object when the route is a string. However, I encounter difficulties when trying to use a regex as a key because it must be a number or a string.
private nodesByRoute: { [key: string]: NavbarItemNode } = {};
this.nodesByRoute[node.route] = node;
To address this issue, I believe the solution may involve something like:
private nodesByRoute: { [key: string | RegExp]: NavbarItemNode } = {};
In my implementation, I receive a route string (e.g. "/category/items"), and if it matches, the corresponding node is returned using the code snippet below:
return this.nodesByRoute[routerLink];
However, I also require support for regex patterns since I may receive inputs like: /items/60
.
In such cases, where "items/" precedes the item number, regex is needed as a key.
Furthermore, I anticipate the need for additional logic when matching keys with routes. While the route will always be a string, the key could potentially be a regex. Therefore, the following approach might not suffice:
return this.nodesByRoute[routerLink];