Skip to content

Instantly share code, notes, and snippets.

@orimdominic
Created May 17, 2024 13:29
Show Gist options
  • Save orimdominic/f592e79aaf057b264367d8a795747990 to your computer and use it in GitHub Desktop.
Save orimdominic/f592e79aaf057b264367d8a795747990 to your computer and use it in GitHub Desktop.
My solution to DonTheDeveloper JavaScript developer interview @ https://www.youtube.com/watch?v=7CWM-jLowpk
const qs = "?foo=bar&zee=zoo&baz&foo=bar2&foo";
function getQueryObject(qs) {
const withoutQueryDelimiter = qs.slice(1);
const kvPairs = withoutQueryDelimiter.split("&");
const output = {};
for (const pair of kvPairs) {
const [key, val] = pair.split("=");
if (!key) continue;
const paramVal = val === undefined ? "true" : val;
if (Array.isArray(output[key])) {
output[key].push(paramVal);
continue;
}
if (output[key]) {
output[key] = [output[key], paramVal];
continue;
}
output[key] = paramVal;
}
return output;
}
// console.log(getQueryObject(qs))
function getQueryString(queryObj) {
let str = "";
const arrayValues = {};
for (const key in queryObj) {
let val;
if (Object.hasOwnProperty.call(queryObj, key)) {
val = queryObj[key];
}
if (!Array.isArray(val) && val === "true") {
str = str.length == 0 ? (str += `${key}`) : (str += `&${key}`);
continue;
}
if (!Array.isArray(val)) {
str =
str.length == 0 ? (str += `${key}=${val}`) : (str += `&${key}=${val}`);
continue;
}
arrayValues[key] = val;
}
for (const key in arrayValues) {
if (Object.hasOwnProperty.call(arrayValues, key)) {
const arr = arrayValues[key];
arr.forEach((val) => {
if (val === "true") {
str = !str.length
? (str += `${key}`)
: (str += `&${key}`);
return;
}
str = !str.length
? (str += `${key}=${val}`)
: (str += `&${key}=${val}`);
return;
});
}
}
return "?" + str;
}
// console.log(
// getQueryString({ foo: ["bar", "bar2", "true"], zee: "zoo", baz: "true" })
// );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment