The application that I am building has the requirement of showing specific content to users whose app version matches the range specified for the content record.
The application uses semantic versioning (e.g. 1.2.3, 1.0.1, 3.7.5).
I want to convert the string value of 1.2.3 to an integer so I can create a range column that holds the min and max version for convenient querying.
Currently I am using the following javascript implementation which results in large numbers and also limits me in the minor and patch version to 999 (the latter is actually okay for me).
export function convertVersionToInt(version) {
const parts = version.split('.')
if (parts.length !== 3) {
throw new Error('Received invalid version string')
}
parts.forEach(part => {
if (part.length > 3) {
throw new Error(`Version string invalid, ${part} is too large.`)
}
})
const [major, minor, patch] = parts
return parseInt(
[major, minor.padStart(3, '0'), patch.padStart(3, '0')].join(''),
10
)
}
export function convertIntVersionToString(v) {
const stringifiedNumber = String(v).padStart(7, '0')
const length = stringifiedNumber.length
const patch = parseInt(stringifiedNumber.substr(length - 3, 3), 10)
const minor = parseInt(stringifiedNumber.substr(length - 6, 3), 10)
const major = stringifiedNumber.substr(0, length - 6)
return `${major}.${minor}.${patch}`
}
const v120 = convertVersionToInt('1.2.0')
const v120S = convertIntVersionToString(v120)
console.log(v120, v120S) // 1002000 '1.2.0'
const v1121 = convertVersionToInt('11.2.1')
const v1121S = convertIntVersionToString(v1121)
console.log(v1121, v1121S) // 11002001 '11.2.0'
const v001 = convertVersionToInt('0.0.1')
const v001s = convertIntVersionToString(v001)
console.log(v001, v001s) // 1 '0.0.1'
I want to know if there is a more efficient way to serialize the semver version to an integer (or other value that allows range queries). A restriction in the amount of digits per version part (major, minor, patch) is fine, however the produced numbers must increase correctly. E.g. number produced by 1.2.0 must be higher than 0.0.1.
Thank you in advance for your input!