Groovy web console

subscribe to the feed Subscribe
to this
site

Version Comparator

Published 5 months ago by founddrama + keithel with tags sort version compare list
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
def versionComparator = { a, b ->
    def VALID_TOKENS = /._/
    a = a.tokenize(VALID_TOKENS)
    b = b.tokenize(VALID_TOKENS)

    for (i in 0..<Math.max(a.size(), b.size())) {
        if (i == a.size()) {
            return b[i].isInteger() ? -1 : 1
        } else if (i == b.size()) {
            return a[i].isInteger() ? 1 : -1
        }

        if (a[i].isInteger() && b[i].isInteger()) {
            int c = (a[i] as int) <=> (b[i] as int)
            if (c != 0) {
                return c
            }
        } else if (a[i].isInteger()) {
            return 1
        } else if (b[i].isInteger()) {
            return -1
        } else {
            int c = a[i] <=> b[i]
            if (c != 0) {
                return c
            }
        }
    }
    return 0
}

versions = [ "5.12.9", "5.15.2.2", "5.9.6", "5.15.2", "5.15.2.1", "5.12.1", "4.8", "5.15.0", "5.15.1" ]
print(versions)
versions = versions.sort(versionComparator).reverse()
print(versions)