[js] custom queryString - OhMinsSup/tip-review GitHub Wiki
/* eslint-disable no-param-reassign */
export const parse = (inputs) => {
inputs = inputs.trim().replace(/^[?#&]/, '');
const ret = Object.create(null);
for (const param of inputs.split('&')) {
const [key, value] = splitOnFirst(param.replace(/\+/g, ' '), '=');
parserForArrayFormat(decode(key), value, ret);
}
return ret;
};
const parserForArrayFormat = (key, value, acc) => {
const result = /\[(\d*)\]$/.exec(key);
key = key.replace(/\[\d*\]$/, '');
if (!result) {
acc[key] = value;
return;
}
if (acc[key] === undefined) {
acc[key] = {};
}
acc[key][result[1]] = value;
};
const splitOnFirst = (string, separator) => {
if (!(typeof string === 'string' && typeof separator === 'string')) {
throw new TypeError('Expected the arguments to be of type `string`');
}
if (separator === '') {
return [];
}
const separatorIndex = string.indexOf(separator);
if (separatorIndex === -1) {
return [];
}
return [
string.slice(0, separatorIndex),
string.slice(separatorIndex + separator.length),
];
};
const decode = (value) => {
return decodeURIComponent(value);
};