Created
January 20, 2017 02:34
-
-
Save primaryobjects/a4d0e4bb6094de458ba87fb0c3b002a2 to your computer and use it in GitHub Desktop.
Compare two version numbers version1 and version2.
This file contains hidden or 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
| /** | |
| * @param {string} version1 | |
| * @param {string} version2 | |
| * @return {number} | |
| */ | |
| var compareVersion = function(version1, version2) { | |
| var result = 0; | |
| // Split version number parts. | |
| var parts1 = version1.split('.').map(function(i) { return parseInt(i); }); | |
| var parts2 = version2.split('.').map(function(i) { return parseInt(i); }); | |
| // Match-up version lengths for comparison. | |
| if (parts1.length < parts2.length) { | |
| for (var i=0; i<parts2.length; i++) { | |
| parts1.push(0); | |
| } | |
| } | |
| if (parts2.length < parts1.length) { | |
| for (i=0; i<parts1.length; i++) { | |
| parts2.push(0); | |
| } | |
| } | |
| // Compare version parts. | |
| for (i in parts1) { | |
| var part1 = parts1[i]; | |
| if (i < parts2.length) { | |
| var part2 = parts2[i]; | |
| if (part1 > part2) { | |
| result = 1; | |
| break; | |
| } | |
| else if (part1 < part2) { | |
| result = -1; | |
| break; | |
| } | |
| } | |
| } | |
| return result; | |
| }; |
This file contains hidden or 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 numbers version1 and version2. | |
| If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. | |
| You may assume that the version strings are non-empty and contain only digits and the . character. | |
| The . character does not represent a decimal point and is used to separate number sequences. | |
| For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision. | |
| Here is an example of version numbers ordering: | |
| 0.1 < 1.1 < 1.2 < 13.37 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment