Skip to content

Commit c9a22bb

Browse files
authored
Refactor parseQueryString for better handling
Enhanced the parseQueryString function to handle empty query strings and duplicate keys. Improved decoding of parameters and ensured proper handling of key-value pairs.
1 parent 3af6a3b commit c9a22bb

1 file changed

Lines changed: 40 additions & 3 deletions

File tree

‎Sprint-2/implement/querystring.js‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,50 @@
11
function parseQueryString(queryString) {
22
const queryParams = {};
3-
if (queryString.length === 0) {
3+
4+
if (!queryString || queryString.length === 0) {
45
return queryParams;
56
}
7+
8+
// Helper to decode '+' as spaces and percent-encoded characters
9+
function decodeParam(str) {
10+
return decodeURIComponent(str.replace(/\+/g, " "));
11+
}
12+
13+
// Split by '&' to get raw key-value pairs
614
const keyValuePairs = queryString.split("&");
715

816
for (const pair of keyValuePairs) {
9-
const [key, value] = pair.split("=");
10-
queryParams[key] = value;
17+
// Ignore empty pairs caused by trailing or duplicate '&' (e.g. "a=1&&b=2&")
18+
if (pair.length === 0) {
19+
continue;
20+
}
21+
22+
let rawKey, rawValue;
23+
const equalIndex = pair.indexOf("=");
24+
25+
if (equalIndex === -1) {
26+
// Key with no '=' (e.g., "key") -> value is empty string
27+
rawKey = pair;
28+
rawValue = "";
29+
} else {
30+
// Split on the FIRST '=' only (handles values containing '=', e.g. "a=b-2")
31+
rawKey = pair.slice(0, equalIndex);
32+
rawValue = pair.slice(equalIndex + 1);
33+
}
34+
35+
const key = decodeParam(rawKey);
36+
const value = decodeParam(rawValue);
37+
38+
// Stretch Goal: Handle duplicate keys by converting to an array
39+
if (Object.prototype.hasOwnProperty.call(queryParams, key)) {
40+
if (Array.isArray(queryParams[key])) {
41+
queryParams[key].push(value);
42+
} else {
43+
queryParams[key] = [queryParams[key], value];
44+
}
45+
} else {
46+
queryParams[key] = value;
47+
}
1148
}
1249

1350
return queryParams;

0 commit comments

Comments
 (0)