hd-utils
Version:
A handy utils for modern JS developers
53 lines (52 loc) • 1.84 kB
JavaScript
import { semverLiteFullRegexPattern } from '../regex/semVerLiteRegex';
/**
* @description Class Definition: SemverLite is defined to handle version strings.
* This is just a very lite semver implementation, if you need the actual thing you can check https://www.npmjs.com/package/semver
*/
class SemverLite {
/**
* @description Compares two versions and returns true if version1 is greater than version2.
*/
static greaterThan(version1, version2) {
const v1 = SemverLite.parse(version1);
const v2 = SemverLite.parse(version2);
return v1 > v2;
}
/**
* @description Compares two versions and returns true if version1 is less than version2.
*/
static lessThan(version1, version2) {
const v1 = SemverLite.parse(version1);
const v2 = SemverLite.parse(version2);
return v1 < v2;
}
/**
* @description Checks if a version string is valid.
*/
static isValid(version) {
return this.versionRegex.test(version);
}
/**
* @description Extracts the numeric version part from a string.
*/
static coerce(version) {
const match = version.match(/\d+(\.\d+)?(\.\d+)?/);
return match ? match[0] : '0.0.0';
}
/**
* @description Returns the smallest version from an array of versions.
*/
static minVersion(versions) {
return versions.reduce((min, v) => SemverLite.lessThan(v, min) ? v : min);
}
/**
* @description Converts a version string into a comparable numeric value.
*/
static parse(version) {
const parts = version.split(/[\.\-\+]/).map(Number);
const [major, minor, patch] = parts;
return major * 1e6 + minor * 1e3 + patch;
}
}
SemverLite.versionRegex = new RegExp(semverLiteFullRegexPattern);
export default SemverLite;