Last active
June 21, 2022 21:28
-
-
Save luan0ap/4ab9447ca581e7daabfd15fa789e7e46 to your computer and use it in GitHub Desktop.
Sort version numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function sortVersions (versions = []) { | |
const sortByVersionNumber = (vA, vB) => { | |
const versionsA = vA.split('.') | |
const versionsB = vB.split('.') | |
const compareVersionNumbers = (index = 0, lastResult = 0) => { | |
const versionNumberA = Number(versionsA[index]) || 0 | |
const versionNumberB = Number(versionsB[index]) || 0 | |
if (lastResult === 0) { | |
if (versionNumberA > versionNumberB) { | |
return compareVersionNumbers(index + 1, 1) | |
} | |
if (versionNumberA < versionNumberB) { | |
return compareVersionNumbers(index + 1, -1) | |
} | |
if (versionNumberA === versionNumberB) { | |
return compareVersionNumbers(index + 1, 0) | |
} | |
} | |
return lastResult | |
} | |
return compareVersionNumbers() | |
} | |
return versions.sort(sortByVersionNumber) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment