-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathqueryString.js
86 lines (74 loc) · 2.25 KB
/
queryString.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* 1st case
* input: '?foo=hello&bar=world'
output: {
foo: 'hello',
bar: 'world'
}
* 2nd case
* input: '?' (if there is no query after ?)
output: should be an empty object like this 👉🏻 {}
* 3rd case
* input: '?foo=hello&bar=world&baz' (if there is no equal sign)
output: {
foo: 'hello',
bar: 'world',
baz: 'true' // send by default true as string
}
* 4th case
* input: '?foo=hello&bar=world&baz&foo=again' (if there is value with the same key, have to save values as array item)
output: {
foo: ['hello', 'again], // save value as array item whick belong to save key
bar: 'world',
baz: 'true'
}
*/
const formatQueryString = (str) => {
// strip off ? and then split by &
const query = str.slice(1).split("&");
const resObj = {};
// iterate through key value pairs, split on = , and save in res object as key value
for (const pair of query) {
let [key, value= 'true'] = pair.split("="); // checking value is truthy or undefined else befault 'true' value (3rd case)
// check if key truthy else send empty object (2nd case)
if (key) {
// if there is value with the same key, have to save values as array item (4th case)
resObj[key] = resObj[key]
? typeof resObj[key] === "string"
? [resObj[key], value]
: [...resObj[key], value]
: value;
// resObj[key] = resObj[key]
// ? Array.isArray(resObj[key])
// ? [...resObj[key], value]
// : [resObj[key], value]
// : value;
}
}
return resObj;
};
console.log("1st case: ", formatQueryString("?foo=hello&bar=world"), {
foo: 'hello',
bar: 'world'
});
// console.log("2nd case: ", formatQueryString("?"), {}); // if there is no query after ?
// console.log("3rd case: ", formatQueryString("?foo=hello&bar=world&baz"), {
// foo: "hello",
// bar: "world",
// baz: "true",
// });
console.log(
"4th case: ",
formatQueryString("?foo=hello&bar=world&baz&foo=again&foo=ok&bar=again&baz&dummy&data=earth"),
{
foo: [ 'hello', 'again', 'ok' ],
bar: [ 'world', 'again' ],
baz: [ 'true', 'true' ],
dummy: 'true',
data: 'earth'
}
);
// test case
// console.log("4th case: ", formatQueryString("?foo=hello&foo"), {
// foo: ["hello", "true"],
// });