Last active
December 5, 2022 05:04
-
-
Save pzinwai/97eb42d6226b0b7b8bb46bbb14347e16 to your computer and use it in GitHub Desktop.
compareSemanticVersions.js
This file contains 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
const compareSemanticVersions = (a: string, b: string) => { | |
// 1. Split the strings into their parts | |
const a1 = a.split('.'); | |
const b1 = b.split('.'); | |
// 2. Contingency in case there's a 4th or 5th version | |
const len = Math.min(a1.length, b1.length); | |
// 3. Look through each version number and compare. | |
for (let i = 0; i < len; i++) { | |
const a2 = +a1[ i ] || 0; | |
const b2 = +b1[ i ] || 0; | |
if (a2 !== b2) { | |
return a2 > b2 ? 1 : -1; | |
} | |
} | |
// 4. We hit this if the all checked versions so far are equal | |
return b1.length - a1.length; | |
}; | |
const versions = [ '7.0.0', '7.0.4', '7.2.0', '7.4.1', '7.3.1' ]; | |
const sorted = versions.sort(compareSemanticVersions); | |
console.log(versions); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment