Skip to content

Commit 9ef7e50

Browse files
committed
javascript string problem solving
1 parent 59502de commit 9ef7e50

1 file changed

Lines changed: 88 additions & 0 deletions

File tree

Interview-Questions/queryString.js

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

0 commit comments

Comments
 (0)