Simplify Semver Version Compare Logic
There's the standard npm semver version comparison library, but I have some simple logic to compare semver versions here: const versionA = '14.8.3'; const versionB = '15.1.1'; cons
Solution 1:
You can use localeCompare
instead, with the numeric
option (with numeric
, comparison is such that "1" < "2" < "10"), which is exactly the logic you're looking for:
const versionA = '14.8.3';
const versionB = '15.1.1';
const versionC = '15.1.2';
const versionD = '15.1.10';
const versionE = '15.2.1';
const versionF = '15.11.1';
constisGreater = (a, b) => {
return a.localeCompare(b, undefined, { numeric: true }) === 1;
};
// first argument version comes later than second argument:console.log(isGreater(versionB, versionA));
console.log(isGreater(versionC, versionB));
console.log(isGreater(versionD, versionC));
console.log(isGreater(versionE, versionD));
console.log(isGreater(versionF, versionE));
console.log('---');
// second comes before first:console.log(isGreater(versionA, versionB));
// same, return value should be false:console.log(isGreater(versionA, versionA));
Or, equivalently, you can pass the locale string
en-US-u-kn-true
as the second parameter instead of { numeric: true }
.
Solution 2:
I believe this is logically the same and shorter, but not exactly stunning in it's simplicity
constisGreater = (a, b) => {
const [majorA, minorA, patchA] = String(a).split('.').map(v =>Number.parseInt(v));
const [majorB, minorB, patchB] = String(b).split('.').map(v =>Number.parseInt(v));
if (majorA !== majorB) {
return majorA > majorB;
}
if (minorA !== minorB) {
return minorA > minorB;
}
return patchA > patchB;
};
Post a Comment for "Simplify Semver Version Compare Logic"