Last active
October 16, 2023 15:34
-
-
Save IBRAHIMDANS/0f7c6d73790eff76606cef0191be2fa4 to your computer and use it in GitHub Desktop.
Compare two version strings to determine if one version is newer than the other
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Compare two version strings to determine if one version is newer than the other. | |
* | |
* @param {string} currentVersion - The current version string to compare. | |
* @param {string} version - The version string to compare with the current version. | |
* @returns {boolean} True if the 'version' is newer than 'currentVersion', false otherwise. | |
* @throws {Error} If either 'currentVersion' or 'version' is not a valid version string. | |
* | |
* @example | |
* // Returns true | |
* isNewVersion('4.98.123', '4.99'); | |
* | |
* @example | |
* // Returns false | |
* isNewVersion('4.99', '4.100.0'); | |
*/ | |
function isNewVersion(currentVersion, version) { | |
if (!currentVersion || !version) return false; | |
const curr = currentVersion.replace(/[^\d.]/g, '').split('.').map(Number); | |
const v = version.replace(/[^\d.]/g, '').split('.').map(Number); | |
const maxLength = Math.max(curr.length, v.length); | |
for (let i = 0; i < maxLength; i++) { | |
const currPart = curr[i] || 0; | |
const vPart = v[i] || 0; | |
if (vPart > currPart) { | |
return true; | |
} else if (vPart < currPart) { | |
return false; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment