Commit 6412f8ae authored by Simon Knox's avatar Simon Knox

Merge branch 'add-sort-option-to-mergeUrlParams' into 'master'

Add sort option to mergeUrlParams

See merge request gitlab-org/gitlab!42561
parents 733323a7 7012486b
...@@ -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