Compare version strings in groovy

后端 未结 11 1938
耶瑟儿~
耶瑟儿~ 2020-11-30 09:50

Hey I have created a Groovy script that will extract the version numbers of some folder. I would then like to compare the version numbers and select the highest.

I g

11条回答
  •  生来不讨喜
    2020-11-30 10:36

    This appears to work

    String mostRecentVersion(List versions) {
      def sorted = versions.sort(false) { a, b -> 
    
        List verA = a.tokenize('.')
        List verB = b.tokenize('.')
    
        def commonIndices = Math.min(verA.size(), verB.size())
    
        for (int i = 0; i < commonIndices; ++i) {
          def numA = verA[i].toInteger()
          def numB = verB[i].toInteger()
          println "comparing $numA and $numB"
    
          if (numA != numB) {
            return numA <=> numB
          }
        }
    
        // If we got this far then all the common indices are identical, so whichever version is longer must be more recent
        verA.size() <=> verB.size()
      }
    
      println "sorted versions: $sorted"
      sorted[-1]
    }
    

    Here is an inadequate set of tests. You should add some more.

    assert mostRecentVersion(['02.2.02.01', '02.2.02.02', '02.2.03.01']) == '02.2.03.01' 
    assert mostRecentVersion(['4', '2']) == '4'
    assert mostRecentVersion(['4.1', '4']) == '4.1'
    assert mostRecentVersion(['4.1', '5']) == '5'
    

    Run this code and the tests in the Groovy console to verify that it works

提交回复
热议问题