Skip to content

Instantly share code, notes, and snippets.

@bc-jasond
Last active September 11, 2017 20:40
Show Gist options
  • Save bc-jasond/fc968f62bc389257a576807db5a39ef3 to your computer and use it in GitHub Desktop.
Save bc-jasond/fc968f62bc389257a576807db5a39ef3 to your computer and use it in GitHub Desktop.
/*
Please implement a function that compares 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
More examples:
1 < 2
1.1 < 1.1.2
1.0.0.0 = 1.0
2.0 < 10.0
Javascript template:
/**
* @param {string} version1
* @param {string} version2
* @return {number}
*/
var compareVersion = function(version1, version2) {
const arr1 = version1.split('.');
const arr2 = version2.split('.');
const maxLevels = Math.max(arr1.length, arr2.length);
for (let i = 0; i < maxLevels; i++) {
// if we're past the end of an array, normalize to 0 for comparison
const versionOneLevel = i >= arr1.length ? 0 : parseInt(arr1[i], 10);
const versionTwoLevel = i >= arr2.length ? 0 : parseInt(arr2[i], 10);
if (versionOneLevel > versionTwoLevel) return 1;
if (versionOneLevel < versionTwoLevel) return -1;
}
return 0;
};
console.log(compareVersion('1.0.1', '1'));
console.log(compareVersion('0.1', '13.37'));
console.log(compareVersion('1', '2'));
console.log(compareVersion('1.1', '1.1.2'));
console.log(compareVersion('1.0.0.0', '1.0'));
console.log(compareVersion('2.0', '10.0'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment