Please review and let me know which version is better. I'm just trying to find any caveats or better ways to accomplish the a version comparison independent from Android and iOS.
Formats accepted: '1.0.0' or '1' formats and an operator, e.g: compareVersion('1', '1.2.0', '>')
export function compareVersion(version1, version2, operator) {
const formattedV1 = version1.split(".");
const formattedV2 = version2.split(".");
let diff = 0;
if (formattedV1.length !== formattedV2.length) {
const lengthDiff = formattedV1.length - formattedV2.length;
for (let index = 0; index < Math.abs(lengthDiff); index += 1) {
if (lengthDiff > 0) {
formattedV2.push("0");
} else {
formattedV1.push("0");
}
}
}
for (let index = 0; index < formattedV1.length; index += 1) {
if (diff === 0) {
const v1 = parseInt(formattedV1[index]);
const v2 = parseInt(formattedV2[index]);
if (isNaN(v1) || isNaN(v2)) {
throw new Error("Problem comparing versions: not a valid number");
}
if (v1 < v2) {
diff = -1;
}
if (v1 > v2) {
diff = 1;
}
}
}
switch (operator) {
case "=":
case "==":
return diff === 0;
case ">=":
return diff >= 0;
case "<=":
return diff <= 0;
case ">":
return diff > 0;
case "<":
return diff < 0;
default:
throw new Error("Problem comparing versions");
}
}
OR
export function compareVersions(a, b, operator) {
const aParts = a.split('.');
const bParts = b.split('.');
const pairs = [];
for (let index = 0; index < Math.max(aParts.length, bParts.length); index += 1) {
pairs.push({
a: parseInt(aParts[index]),
b: parseInt(bParts[index]),
});
}
let diff = 0;
pairs.forEach((pair) => {
if (diff === 0) {
if (pair.a > pair.b) {
diff = 1;
}
if (pair.b > pair.a) {
diff = -1;
}
if (!isNaN(pair.a) && isNaN(pair.b)) {
diff = 1;
}
if (isNaN(pair.a) && !isNaN(pair.b)) {
diff = -1;
}
}
});
switch (operator) {
case '=':
case '==':
return diff === 0;
case '>=':
return diff >= 0;
case '<=':
return diff <= 0;
case '>':
return diff > 0;
case '<':
return diff < 0;
default:
throw new Error('Problem comparing versions');
}
}