|
4 | 4 | // - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf |
5 | 5 | // - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice |
6 | 6 |
|
| 7 | +// Sprint-2/implement/querystring.js |
| 8 | + |
7 | 9 | function parseQueryString(queryString) { |
8 | 10 | const queryParams = {}; |
9 | | - |
10 | | - // Returns early if the string is empty |
11 | | - if (queryString.length === 0) { |
12 | | - return queryParams; |
13 | | - } |
14 | | - |
15 | | - const keyValuePairs = queryString.split("&"); |
16 | | - |
17 | | - for (const pair of keyValuePairs) { |
18 | | - // Finds only the first "=" since values may contain "=" too |
19 | | - const firstEqualsIndex = pair.indexOf("="); |
20 | | - |
21 | | - const key = pair.slice(0, firstEqualsIndex); |
22 | | - const value = pair.slice(firstEqualsIndex + 1); |
23 | | - |
24 | | - queryParams[key] = value; |
| 11 | + if (!queryString) return queryParams; |
| 12 | + |
| 13 | + const pairs = queryString.split("&"); |
| 14 | + |
| 15 | + for (const pair of pairs) { |
| 16 | + const equalsIndex = pair.indexOf("="); |
| 17 | + |
| 18 | + if (equalsIndex === -1) { |
| 19 | + // Handle keys with no value |
| 20 | + const key = decodeURIComponent(pair); |
| 21 | + queryParams[key] = null; |
| 22 | + } else { |
| 23 | + const key = decodeURIComponent(pair.slice(0, equalsIndex)); |
| 24 | + const value = decodeURIComponent(pair.slice(equalsIndex + 1)); |
| 25 | + queryParams[key] = value; |
| 26 | + } |
25 | 27 | } |
26 | 28 |
|
27 | 29 | return queryParams; |
|
0 commit comments