Skip to content

Commit 97a6df5

Browse files
author
Enice-Codes
committed
Complete querystring project
1 parent 351dfc6 commit 97a6df5

2 files changed

Lines changed: 30 additions & 14 deletions

File tree

‎Sprint-2/implement/querystring.js‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,29 @@
1+
function decodeComponent(str) {
2+
return decodeURIComponent(str.replace(/\+/g, " "));
3+
}
4+
15
function parseQueryString(queryString) {
2-
const queryParams = {};
36
if (queryString.length === 0) {
4-
return queryParams;
7+
return {};
58
}
6-
const keyValuePairs = queryString.split("&");
79

8-
for (const pair of keyValuePairs) {
9-
const [key, value] = pair.split("=");
10-
queryParams[key] = value;
10+
const params = {};
11+
const pairs = queryString.split("&").filter((pair) => pair !== "");
12+
13+
for (const pair of pairs) {
14+
const [rawKey, ...rest] = pair.split("=");
15+
const key = decodeComponent(rawKey);
16+
const value = decodeComponent(rest.join("="));
17+
18+
if (key in params) {
19+
params[key] = [].concat(params[key], value);
20+
} else {
21+
params[key] = value;
22+
}
1123
}
1224

13-
return queryParams;
25+
return params;
26+
1427
}
1528

16-
module.exports = parseQueryString;
29+
module.exports = parseQueryString;

‎Sprint-2/implement/querystring.test.js‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@
22
// Unfortunately, it contains several bugs!
33
// Below are some test cases the implementation doesn't handle well.
44
// Fix the implementation for these tests, and try to think of as many other edge cases as possible - write tests and fix those too.
5-
6-
const parseQueryString = require("./querystring.js")
5+
const parseQueryString = require("./querystring");
76

87
test("should parse values containing '='", () => {
98
expect(parseQueryString("equation=a=b-2")).toEqual({
@@ -30,19 +29,23 @@ test("should decode percent-encoded characters", () => {
3029
$half: "1/2",
3130
});
3231
});
33-
3432
test("should replace '+' by ' '", () => {
3533
expect(parseQueryString("full+name=John+Doe")).toEqual({
3634
"full name": "John Doe",
3735
});
3836
});
3937

38+
test("should return {} for an empty string", () => {
39+
expect(parseQueryString("")).toEqual({});
40+
});
41+
4042
// Stretch exercise: Handling query strings that contain identical keys
4143

42-
// Delete this test if you are not working on this optional case
4344
test("should store values of a key in an array when the key has 2 or more values", () => {
44-
expect(parseQueryString("key=value1&key=value2&key=value3&foo=bar")).toEqual({
45+
expect(
46+
parseQueryString("key=value1&key=value2&key=value3&foo=bar")
47+
).toEqual({
4548
key: ["value1", "value2", "value3"],
4649
foo: "bar",
4750
});
48-
});
51+
});

0 commit comments

Comments
 (0)