Skip to content

Instantly share code, notes, and snippets.

@pzinwai
Last active December 5, 2022 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pzinwai/97eb42d6226b0b7b8bb46bbb14347e16 to your computer and use it in GitHub Desktop.
Save pzinwai/97eb42d6226b0b7b8bb46bbb14347e16 to your computer and use it in GitHub Desktop.
compareSemanticVersions.js
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