In a moment of boredom, I decided to write two methods, one of which would create a query string, while the other would parse it, the constraint I imposed on myself being that each method could not exceed one statement. The result is by no means something I'd ever consider using at work or in my personal projects, for that matter; my reason for posting this question is that I'd like to know how, given the constraint I set for myself, the code could be improved on? Like, what's the best code you could write to solve the problem at hand - creating and parsing a query string - without having the two methods constitute more than 2 statements? I'm sure you could do it in a much more elegant manner, and I'm looking forward to any feedback coming my way!
const createQueryString = input => encodeURI(`?${Object.keys(input).map(name
=> `${name}=${input[name]}`).join('&')}`);
const queryString = createQueryString({
name: 'Darrell',
age: '3 2',
nationality: 'Swedish'
});
console.log(queryString);
const parseQueryString = (input, obj = Object.create(null)) =>
decodeURI(input.slice(input.indexOf('?') + 1,
input.length)).split('&').map(entry => [
[entry.split('=')[0]],
[entry.split('=')[1]]
]).reduce((obj, query) => Object.assign(obj, {
[query[0][0]]: query[1][0]
}), {});
const parsedQueryString = parseQueryString(queryString);
console.log(parsedQueryString);