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