qs icon indicating copy to clipboard operation
qs copied to clipboard

Add support for stringify options sort: boolean

Open Zclhlmgqzc opened this issue 3 years ago • 5 comments

Add support for stringify options sort: boolean

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

if (sort === true) {
  objKeys = keys.sort()
} else if (sort) { ... }

Zclhlmgqzc avatar Jun 08 '21 05:06 Zclhlmgqzc

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.

ljharb avatar Jun 09 '21 20:06 ljharb

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%

Zclhlmgqzc avatar Jun 10 '21 03:06 Zclhlmgqzc

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?

ljharb avatar Jun 10 '21 14:06 ljharb

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

Zclhlmgqzc avatar Jun 10 '21 14:06 Zclhlmgqzc

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?

ljharb avatar Jun 12 '21 20:06 ljharb