Commit 7012486b authored by Eulyeon Ko's avatar Eulyeon Ko

Add sort option to mergeUrlParams

When sort option is given, mergeUrlParams
alphabetically sorts the params in ascending order (a to z).
parent f3cd5856
...@@ -75,7 +75,7 @@ export function getParameterValues(sParam, url = window.location) { ...@@ -75,7 +75,7 @@ export function getParameterValues(sParam, url = window.location) {
* @param {Boolean} options.spreadArrays - split array values into separate key/value-pairs * @param {Boolean} options.spreadArrays - split array values into separate key/value-pairs
*/ */
export function mergeUrlParams(params, url, options = {}) { export function mergeUrlParams(params, url, options = {}) {
const { spreadArrays = false } = options; const { spreadArrays = false, sort = false } = options;
const re = /^([^?#]*)(\?[^#]*)?(.*)/; const re = /^([^?#]*)(\?[^#]*)?(.*)/;
let merged = {}; let merged = {};
const [, fullpath, query, fragment] = url.match(re); const [, fullpath, query, fragment] = url.match(re);
...@@ -108,7 +108,9 @@ export function mergeUrlParams(params, url, options = {}) { ...@@ -108,7 +108,9 @@ export function mergeUrlParams(params, url, options = {}) {
Object.assign(merged, params); Object.assign(merged, params);
const newQuery = Object.keys(merged) const mergedKeys = sort ? Object.keys(merged).sort() : Object.keys(merged);
const newQuery = mergedKeys
.filter(key => merged[key] !== null) .filter(key => merged[key] !== null)
.map(key => { .map(key => {
let value = merged[key]; let value = merged[key];
......
...@@ -161,6 +161,15 @@ describe('URL utility', () => { ...@@ -161,6 +161,15 @@ describe('URL utility', () => {
); );
}); });
it('sorts params in alphabetical order with sort option', () => {
expect(mergeUrlParams({ c: 'c', b: 'b', a: 'a' }, 'https://host/path', { sort: true })).toBe(
'https://host/path?a=a&b=b&c=c',
);
expect(
mergeUrlParams({ alpha: 'alpha' }, 'https://host/path?op=/&foo=bar', { sort: true }),
).toBe('https://host/path?alpha=alpha&foo=bar&op=%2F');
});
describe('with spread array option', () => { describe('with spread array option', () => {
const spreadArrayOptions = { spreadArrays: true }; const spreadArrayOptions = { spreadArrays: true };
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment