version-compare
Version:
Comparator to determine if a version is less than, equivalent to, or greater than another version
30 lines (29 loc) • 1.16 kB
JavaScript
export var VersionIs;
(function (VersionIs) {
VersionIs[VersionIs["LessThan"] = -1] = "LessThan";
VersionIs[VersionIs["EqualTo"] = 0] = "EqualTo";
VersionIs[VersionIs["GreaterThan"] = 1] = "GreaterThan";
})(VersionIs || (VersionIs = {}));
/**
* Compare two versions quickly.
* @param current Is this version greater, equal to, or less than the other?
* @param other The version to compare against the current version
* @returns 1 if current is greater than other, 0 if they are equal or equivalent, and -1 if current is less than other
*/
export default function versionCompare(current, other) {
const cp = String(current).split('.');
const op = String(other).split('.');
for (let depth = 0; depth < Math.min(cp.length, op.length); depth++) {
const cn = Number(cp[depth]);
const on = Number(op[depth]);
if (cn > on)
return VersionIs.GreaterThan;
if (on > cn)
return VersionIs.LessThan;
if (!isNaN(cn) && isNaN(on))
return VersionIs.GreaterThan;
if (isNaN(cn) && !isNaN(on))
return VersionIs.LessThan;
}
return VersionIs.EqualTo;
}