Technical Interview Challenge: The "Legacy-Link" Query Parser
Context
Before the modern URL and URLSearchParams APIs were standardized, frontend engineers had to manually manipulate the "Search" portion of a URL. Even today, when building high-performance micro-utilities or supporting highly restricted legacy environments (like older embedded browsers or specific enterprise runtimes), you cannot always rely on native browser APIs.
The challenge is to build a robust Data Structure that can handle the "Multi-Value" nature of query parameters—where a single key can represent multiple values (e.g., ?filter=red&filter=blue)—while maintaining a clean, predictable interface for modification and serialization.
Problem Statement
Implement a class MyURLSearchParams that mimics the standard browser API for parsing and manipulating URL query strings. Your implementation must handle encoding/decoding, multiple values per key, and state synchronization.
Requirements:
Stateful Storage: Store parameters in a way that preserves multiple values for a single key and maintains the order of insertion.
Core Methods:
constructor(init): Accepts a query string (optionally starting with?).get(key)/getAll(key): Retrieves the first value or all values associated with a key.set(key, value): Replaces all existing values for a key with a single new value.append(key, value): Adds a new value to a key without removing existing ones.delete(key): Removes the key and all its associated values entirely.
Utility Methods:
has(key): Returns a boolean indicating if a key exists.toString(): Serializes the current state back into a URL-encoded query string.
Edge Case Handling: Handle empty strings, malformed pairs (like
key=), and ensure values are properly decoded/encoded.
Example Use Cases
Example 1: Parsing and Retrieval
JavaScript
const params = new MyURLSearchParams("?user=rahul&role=admin&role=editor");
params.get("role"); // Expected: "admin"
params.getAll("role"); // Expected: ["admin", "editor"]Example 2: Modification and State
JavaScript
params.set("user", "gemini");
params.append("role", "viewer");
params.getAll("role"); // Expected: ["admin", "editor", "viewer"]
params.toString(); // Expected: "user=gemini&role=admin&role=editor&role=viewer"Example 3: Deletion
JavaScript
params.delete("role");
params.has("role"); // Expected: false
params.toString(); // Expected: "user=gemini"Interview Evaluation Criteria
Data Structure Choice: Will you use a plain
Object, aMap, or aMap<string, string[]>? How does your choice impact thetoString()order and theappend()logic?Encoding/Decoding: Do you correctly use
decodeURIComponentduring parsing andencodeURIComponentduring serialization to handle special characters (like spaces,&, or=)?Order Preservation: When calling
toString(), are the parameters returned in the order they were originally parsed or appended?Parsing Logic: How do you handle edge cases like
?key(no equals sign) or&&(empty segments)?