Skip to content

Commit

Permalink
Do not sort when sort option is set to false (#155)
Browse files Browse the repository at this point in the history
  • Loading branch information
vicapow authored and sindresorhus committed Oct 2, 2018
1 parent 5b4ce87 commit b20493e
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
16 changes: 11 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,13 +179,19 @@ exports.stringify = (obj, options) => {

options = Object.assign(defaults, options);

if (options.sort === false) {
options.sort = () => {};
const formatter = encoderForArrayFormat(options);

if (!obj) {
return '';
}

const formatter = encoderForArrayFormat(options);
const keys = Object.keys(obj);

if (options.sort !== false) {
keys.sort(options.sort);
}

return obj ? Object.keys(obj).sort(options.sort).map(key => {
return keys.map(key => {
const value = obj[key];

if (value === undefined) {
Expand All @@ -211,7 +217,7 @@ exports.stringify = (obj, options) => {
}

return encode(key, options) + '=' + encode(value, options);
}).filter(x => x.length > 0).join('&') : '';
}).filter(x => x.length > 0).join('&');
};

exports.parseUrl = (input, options) => {
Expand Down
18 changes: 18 additions & 0 deletions test/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,24 @@ test('should sort keys in given order', t => {
t.is(m.stringify({a: 'foo', b: 'bar', c: 'baz'}, {sort}), 'c=baz&a=foo&b=bar');
});

test('should not sort when sort is false', t => {
const object = {
story: 'a',
patch: 'b',
deployment: 'c',
lat: 10,
lng: 20,
sb: 'd',
sc: 'e',
mn: 'f',
ln: 'g',
nf: 'h',
srs: 'i',
destination: 'g'
};
t.is(m.stringify(object, {sort: false}), 'story=a&patch=b&deployment=c&lat=10&lng=20&sb=d&sc=e&mn=f&ln=g&nf=h&srs=i&destination=g');
});

test('should disable sorting', t => {
t.is(m.stringify({
c: 'foo',
Expand Down

0 comments on commit b20493e

Please sign in to comment.