diff --git a/index.js b/index.js index 09711e9d..5df1ca16 100644 --- a/index.js +++ b/index.js @@ -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) { @@ -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) => { diff --git a/test/stringify.js b/test/stringify.js index 4e4e28bb..0302b507 100644 --- a/test/stringify.js +++ b/test/stringify.js @@ -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',