Skip to content

Commit

Permalink
Add sort option (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
msn0 authored and sindresorhus committed Feb 3, 2018
1 parent 6404fd9 commit 334152b
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
6 changes: 5 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,13 @@ exports.stringify = function (obj, opts) {

opts = objectAssign(defaults, opts);

if (opts.sort === false) {
opts.sort = function () {};
}

var formatter = encoderForArrayFormat(opts);

return obj ? Object.keys(obj).sort().map(function (key) {
return obj ? Object.keys(obj).sort(opts.sort).map(function (key) {
var val = obj[key];

if (val === undefined) {
Expand Down
25 changes: 25 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,31 @@ queryString.stringify({foo: [1,2,3]});
// => foo=1&foo=2&foo=3
```

#### sort

Type: `Function` `boolean`

Supports both `Function` as a custom sorting function or `false` for disabling sorting.

- `Function`:

```js
const order = ['c', 'a', 'b'];
queryString.stringify({ a: 1, b: 2, c: 3}, {
sort: (m, n) => order.indexOf(m) >= order.indexOf(n)
});
// => 'c=3&a=1&b=2'
```

- `false`:

```js
queryString.stringify({ b: 1, c: 2, a: 3}, {sort: false});
// => 'c=3&a=1&b=2'
```

If omitted, keys are sorted using `Array#sort`, which means, converting them to strings and comparing strings in Unicode code point order.

### .extract(*string*)

Extract a query string from a URL that can be passed into `.parse()`.
Expand Down
17 changes: 17 additions & 0 deletions test/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,20 @@ test('array stringify representation with array indexes and sparse array', t =>
a[10] = 'three';
t.is(fn.stringify({bar: a}, {arrayFormat: 'index'}), 'bar[0]=one&bar[1]=two&bar[2]=three');
});

test('should sort keys in given order', t => {
const order = ['c', 'a', 'b'];
const sort = (key1, key2) => order.indexOf(key1) >= order.indexOf(key2);

t.is(fn.stringify({a: 'foo', b: 'bar', c: 'baz'}, {sort}), 'c=baz&a=foo&b=bar');
});

test('should disable sorting', t => {
t.is(fn.stringify({
c: 'foo',
b: 'bar',
a: 'baz'
}, {
sort: false
}), 'c=foo&b=bar&a=baz');
});

0 comments on commit 334152b

Please sign in to comment.