Skip to content

Commit 018d711

Browse files
added the the test cases of a program accept empty string as key or value and updated the function
1 parent cfcdacd commit 018d711

2 files changed

Lines changed: 16 additions & 8 deletions

File tree

‎Sprint-2/implement/querystring.js‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,22 @@ function parseQueryString(queryString) {
33
if (queryString.length === 0) {
44
return queryParams;
55
}
6-
const keyValuePairs = queryString.replace(/\+/g," ").split("&").filter((pair)=> pair !=='');
6+
const keyValuePairs = queryString
7+
.replace(/\+/g, " ")
8+
.split("&")
9+
.filter((pair) => pair !== "");
710

811
for (const pair of keyValuePairs) {
912
const indexFirstEqual = pair.indexOf("=");
10-
const [key, value]=[
11-
decodeURIComponent(pair.slice(0,indexFirstEqual)),
12-
decodeURIComponent(pair.slice(indexFirstEqual+1))
13-
]
14-
queryParams[key]=value;
15-
13+
let key, value;
14+
if (indexFirstEqual === -1) {
15+
key = decodeURIComponent(pair);
16+
value = "";
17+
} else {
18+
((key = decodeURIComponent(pair.slice(0, indexFirstEqual))),
19+
(value = decodeURIComponent(pair.slice(indexFirstEqual + 1))));
20+
}
21+
queryParams[key] = value;
1622
}
1723

1824
return queryParams;

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
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.
55

6-
const parseQueryString = require("./querystring.js")
6+
const parseQueryString = require("./querystring.js");
77

88
test("should parse values containing '='", () => {
99
expect(parseQueryString("equation=a=b-2")).toEqual({
@@ -20,6 +20,8 @@ test("should ignore empty key-value pairs", () => {
2020

2121
test("should accept empty string as key or as value", () => {
2222
expect(parseQueryString("=value")).toEqual({ "": "value" });
23+
expect(parseQueryString("key")).toEqual({ key: "" });
24+
expect(parseQueryString("key=")).toEqual({ key: "" });
2325
expect(parseQueryString("=")).toEqual({ "": "" });
2426
});
2527

0 commit comments

Comments
 (0)