Descolada / AHK-v2-libraries

Useful libraries for AHK v2
MIT License
94 stars 9 forks source link

Array.Sort: Incorrect negative numerical sorting of array values & Key parameter does not work with Map objects #7

Closed Ragnar-F closed 9 months ago

Ragnar-F commented 9 months ago

For the incorrect negative numerical sorting of array values, see the following example:

#Include Array.ahk
MsgBox ["0.0", "-0.08", "-0.16", "-0.34"].sort().join("`n")
; Shows:
; -0.08
; -0.16
; -0.34
; 0.0

MsgBox Sort("0.0`n-0.08`n-0.16`n-0.34", "N")
; Shows:
; -0.34
; -0.16
; -0.08
; 0.0

More a wish than a bug, but definitely useful: By replacing fieldValue1.%key% with (fieldValue1 is Map ? fieldValue1[key] : fieldValue1.%key%) and fieldValue2.%key% with (fieldValue2 is Map ? fieldValue2[key] : fieldValue2.%key%), the Key parameter also works for Map objects.

Descolada commented 9 months ago

Good catch! Of course the sorting callback return value is converted to an integer, so floats with a difference <1.0 were considered equal... This example code from Sort docs has the same issue:

MyVar := "5,3,7,9,1,13,999,-4"
MsgBox Sort(MyVar, "D,", IntegerSort)
IntegerSort(a1, a2, *)
{
    return a1 - a2  ; Sorts in ascending numeric order. This method works only if the difference is never so large as to overflow a signed 64-bit integer.
}

This outputs -4,1,3,5,7,9,13,999 in ascending order as expected. However, replace the input string with 0.0,-0.08,-0.16,-0.34 and the result is 0.0,-0.08,-0.16,-0.34, obviously incorrect.

I've pushed a fix for this, and also added a way to sort by Map keys (actually any object with __Item).