wurstscript / WurstStdlib2

WurstScript Standard Library Version 2
Apache License 2.0
55 stars 53 forks source link

String comparison function #427

Closed jmrico01 closed 11 months ago

jmrico01 commented 11 months ago

I wanted to sort a LinkedList<string> and was looking for an out-of-the-box string comparison function, something like

function stringCompare(string a, string b) returns int
    ...

I couldn't find anything in String.wurst or StringUtils.wurst. Does this exist? If not, is this something that could be added? Plus maybe a builtin LinkedList<string> comparator for sort, like the ones for int and real.

Admittedly it's kind of nasty to implement this, as the char/string -> int conversions in JASS are 💩 . In the meantime, this is my very rough implementation I'll be using (any characters outside the charset in String.wurst convert to -1 and therefore compare as equal).

// Basic lexicographic string comparison.
public function stringCompareLex(string s1, string s2) returns int
    let s1Len = s1.length()
    let s2Len = s2.length()
    for int i = 0 to min(s1Len, s2Len)
        // TODO seems slow, but whatever
        let char1Int = s1.charAt(i).toCharsetInt()
        let char2Int = s2.charAt(i).toCharsetInt()
        if char1Int < char2Int
            return -1
        else if char1Int > char2Int
            return 1

    if s1Len < s2Len
        return -1
    else if s1Len > s2Len
        return 1
    return 0
Frotty commented 11 months ago

I don't think a string comparison exists, your implementation seems fine, could make a PR for it.