API Endpoint Path Normalizer
Gupshup's platform handles a vast ecosystem of APIs, requiring robust and consistent management of endpoint paths. Ensuring a canonical and absolute representation of these paths is crucial for reliable routing, security, and logging across various services. This problem challenges you to implement a function that normalizes a sequence of raw path segments into a standard, absolute API endpoint path.
Implement a function normalizeApiPath that takes an array of string segments and returns the canonical absolute path. Your implementation must adhere to the following rules:
"users", "v1") represent valid directory or resource names and should be included in the path..): Segments consisting solely of . should be ignored as they represent the current directory and do not alter the path...): Segments consisting solely of .. should navigate up one level in the path. If the path is already at the root (i.e., empty), .. has no effect./): A segment consisting solely of / acts as a reset. When encountered, it signifies that subsequent segments should be processed relative to the root, effectively clearing any previously accumulated path segments./. It should not end with a / unless it is the root path / itself.segments: string[]
"api", "messages"), ".", "..", or "/".string
segments array will not be empty, and each segment will be a non-empty string./ characters within a segment (e.g., you won't receive "users/profile" as a single segment).Examples
Example 1
Input:
segments = ["/", "home", ".", "user", "..", "profile"]
Output:
"/home/profile"
Note:
Starting at root, home adds /home. . is ignored. user adds /home/user. .. removes user to become /home. Finally, profile adds /home/profile.
Example 2
Input:
segments = ["/", "..", "var", "log", "..", "tmp"]
Output:
"/var/tmp"
Note:
Starting at root, .. has no effect. var adds /var. log adds /var/log. .. removes log to become /var. Finally, tmp adds /var/tmp.
Example 3
Input:
segments = ["home", "user", "/", "api", "v1", "..", "status"]
Output:
"/api/status"
Note:
Implicitly starting at root, home then user would form /home/user. However, _ resets the path to root. Then api adds /api, v1 adds /api/v1. .. removes v1 to become /api. Finally, status adds /api/status.
Constraints
1 <= segments.length <= 10^41 <= segments[i].length <= 100segments[i] consists of English letters, digits, . (dot), .. (double dot), or / (slash)./ characters within itself (they are already pre-split).., .., /, valid names) and constructs the canonical path... from the root, and the behavior of / as a path reset.Loading editor...