Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for stringify options sort: boolean #414

Open
Zclhlmgqzc opened this issue Jun 8, 2021 · 5 comments
Open

Add support for stringify options sort: boolean #414

Zclhlmgqzc opened this issue Jun 8, 2021 · 5 comments

Comments

@Zclhlmgqzc
Copy link

Add support for stringify options sort: boolean

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

if (sort === true) {
  objKeys = keys.sort()
} else if (sort) { ... }
@ljharb
Copy link
Owner

ljharb commented Jun 9, 2021

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
Copy link
Author

Zclhlmgqzc commented Jun 10, 2021

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
Copy link
Owner

ljharb commented Jun 10, 2021

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
Copy link
Author

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
Copy link
Owner

ljharb commented Jun 12, 2021

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants