Question
· May 10, 2023

Sort array of version numbers in ObjectScript?

I'm trying to write an ObjectScript function that sorts version numbers to help learn ObjectScript. This is all I can think of after staring at VS Code for a while, but I don't know where to go with it. Can someone please help out with a tip? The goal is to take something like ["1.4.5", "0.5.3", "6.3.2", "1.2.4"] and turn it into ["0.5.3", "1.2.4", "1.4.5", "6.3.2"]

ClassMethod SortVersion(input As %String[]) As %String[] {
    Set sorted = []

    for i=1:1:input.%Size() {
        Set version = input.Get(i)

        Set major = $NUMBER($PIECE(version, ".", 1))
        Set minor = $NUMBER($PIECE(version, ".", 2))
        Set patch = $NUMBER($PIECE(version, ".", 3))
    }
}
Discussion (4)1
Log in or sign up to continue

ChatGPT recommends: 

ClassMethod SortVersion(input As %String[]) As %String[] {
    Set sorted = []

    for i=1:1:input.%Size() {
        Set version = input.Get(i)

        Set major = $NUMBER($PIECE(version, ".", 1))
        Set minor = $NUMBER($PIECE(version, ".", 2))
        Set patch = $NUMBER($PIECE(version, ".", 3))

        // Create a new dynamic object to store the version number and its corresponding string representation
        Set versionObj = {}
        Set versionObj.version = version
        Set versionObj.major = major
        Set versionObj.minor = minor
        Set versionObj.patch = patch

        // Add the version object to the 'sorted' array
        Do sorted.Insert(versionObj)
    }

    // Sort the 'sorted' array based on major, minor, and patch values
    Do sorted.Sort("major", "minor", "patch")

    // Create a new array to store the sorted version numbers
    Set sortedVersions = []

    // Iterate over the sorted objects and extract the version number
    For i=1:1:sorted.%Size() {
        Set versionObj = sorted.GetAt(i)
        Do sortedVersions.Insert(versionObj.version)
    }

    Quit sortedVersions
}

Seems to make sense.  Usage is:

Set input = ["1.4.5", "0.5.3", "6.3.2", "1.2.4"]
Set sortedVersions = ##class(YourClassName).SortVersion(input)
Write !, sortedVersions.%ToString()