fix[orderBy, sortBy]: keep sort order consistent when values contain NaN - #2133
Open
minseonkkim wants to merge 2 commits into
Open
minseonkkim wants to merge 2 commits into
minseonkkim wants to merge 2 commits into
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
This branch had an error being deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
When the sort key contains
NaN,orderByandsortByleave the array partially unsorted.compareAscendinginsrc/_internal/compareValues.tscompares regular values with<and>. Every comparison involvingNaNreturnsfalse, soNaNis treated as equal to every value. This breaks the transitivity the comparator relies on (3 == NaN,NaN == 0, but3 > 0), and the sort produces an inconsistent result. Elements before theNaNare not sorted at all.This can easily happen in practice, for example when a numeric field comes from a failed
parseFloator a0 / 0calculation.I found this while reading the code, so there is no related issue.
Changes
src/_internal/compareValues.ts: giveNaNits own rank, so it never reaches the</>comparison. The order is now regular values <NaN<null<undefined, following the existing approach fornullandundefined.src/array/orderBy.spec.ts: add tests for ascending, descending, and mixedNaN/null/undefinedcases.The new tests fail on
mainand pass with this change.I placed
NaNbeforenullandundefinedbecauseNaNis still a number, whilenullandundefinedmean the value is missing. Lodash uses a different order (null<undefined<NaN), so I'm happy to change it if you prefer that.es-toolkit/compathas its owncompareValues, so it is not affected.Benchmark results
main
This branch