ljharb / qs

A querystring parser with nesting support
BSD 3-Clause "New" or "Revised" License
8.5k stars 729 forks source link

Add support for stringify options sort: boolean #414

Open Zclhlmgqzc opened 3 years ago

Zclhlmgqzc commented 3 years ago

Add support for stringify options sort: boolean

qs.stringify(data, {
  sort: true
})

if (sort === true) {
  objKeys = keys.sort()
} else if (sort) { ... }
ljharb commented 3 years ago

To be clear, you want true to be a shortcut for the default comparator? that seems like it might be a footgun - you can always provide (a, b) => String(b).localeCompare(a) if that's what you want.

Zclhlmgqzc commented 3 years ago

To be clear, you want true to be a shortcut for the default comparator? that seems like it might be a footgun - you can always provide (a, b) => String(b).localeCompare(a) if that's what you want.

Lexicographical Order


console.log(['ab', 'Bb', 'aB', 'ac'].sort())
// [ 'Bb', 'aB', 'ab', 'ac' ]
console.log(['ab', 'Bb', 'aB', 'ac'].sort((a, b) => a.localeCompare(b)))
// [ 'ab', 'aB', 'ac', 'Bb' ]
console.log(
  ['ab', 'Bb', 'aB', 'ac'].sort((a, b) => {
    if (a > b) {
      return 1
    } else if (a < b) {
      return -1
    }

    return 0
  })
)
// [ 'Bb', 'aB', 'ab', 'ac' ]

native sort increases performance by 10%

ljharb commented 3 years ago

Ah, sure, it’d be b - a if that’s what you want.

I’m not sure why performance matters for the tiny number of keys anyone would be interacting with in a query string?

Zclhlmgqzc commented 3 years ago

Ah, sure, it’d be b - a if that’s what you want.

I’m not sure why performance matters for the tiny number of keys anyone would be interacting with in a query string?

b - a is NaN

ljharb commented 3 years ago

lol ah, right, it's the code you provided that would be needed.

regardless tho, what's the use case? When wouldn't you want localeCompare, and when would it be hard to provide the exact comparator you need?