Skip to content

Commit

Permalink
Preserve appearance order while handling multiple values (sindresorhu…
Browse files Browse the repository at this point in the history
  • Loading branch information
doochik authored and sindresorhus committed Jan 14, 2017
1 parent 4926913 commit 91d4d04
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
12 changes: 7 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,11 +96,11 @@ function encode(value, opts) {
return value;
}

function sorter(input) {
function keysSorter(input) {
if (Array.isArray(input)) {
return input.sort();
} else if (typeof input === 'object') {
return sorter(Object.keys(input)).sort(function (a, b) {
return keysSorter(Object.keys(input)).sort(function (a, b) {
return Number(a) - Number(b);
}).map(function (key) {
return input[key];
Expand Down Expand Up @@ -148,10 +148,12 @@ exports.parse = function (str, opts) {
});

return Object.keys(ret).sort().reduce(function (result, key) {
if (Boolean(ret[key]) && typeof ret[key] === 'object') {
result[key] = sorter(ret[key]);
var val = ret[key];
if (Boolean(val) && typeof val === 'object' && !Array.isArray(val)) {
// Sort object keys, not values
result[key] = keysSorter(val);
} else {
result[key] = ret[key];
result[key] = val;
}

return result;
Expand Down
15 changes: 15 additions & 0 deletions test/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,21 @@ test('handle multiple of the same key', t => {
t.deepEqual(fn.parse('foo=bar&foo=baz'), {foo: ['bar', 'baz']});
});

test('handle multiple values and preserve appearence order', t => {
t.deepEqual(fn.parse('a=value&a='), {a: ['value', '']});
t.deepEqual(fn.parse('a=&a=value'), {a: ['', 'value']});
});

test('handle multiple values and preserve appearance order with brackets', t => {
t.deepEqual(fn.parse('a[]=value&a[]=', {arrayFormat: 'bracket'}), {a: ['value', '']});
t.deepEqual(fn.parse('a[]=&a[]=value', {arrayFormat: 'bracket'}), {a: ['', 'value']});
});

test('handle multiple values and preserve appearance order with indexes', t => {
t.deepEqual(fn.parse('a[0]=value&a[1]=', {arrayFormat: 'index'}), {a: ['value', '']});
t.deepEqual(fn.parse('a[1]=&a[0]=value', {arrayFormat: 'index'}), {a: ['value', '']});
});

test('query strings params including embedded `=`', t => {
t.deepEqual(fn.parse('?param=http%3A%2F%2Fsomeurl%3Fid%3D2837'), {param: 'http://someurl?id=2837'});
});
Expand Down

0 comments on commit 91d4d04

Please sign in to comment.