I am able to pare version numbers correctly in JavaScript without having to split and check each decimal numbers. How is it working?
("2.0.1" > "2.1.0")
false
("2.2.1" > "2.1.0")
true
("2.5.1" > "2.0.5")
true
Thanks.
I am able to pare version numbers correctly in JavaScript without having to split and check each decimal numbers. How is it working?
("2.0.1" > "2.1.0")
false
("2.2.1" > "2.1.0")
true
("2.5.1" > "2.0.5")
true
Thanks.
Share Improve this question asked Jan 15, 2016 at 12:21 user235273user235273 3-
1
semver
– thefourtheye Commented Jan 15, 2016 at 12:23 - 1 It's actually doing a character-by-character string parison. – Matt Commented Jan 15, 2016 at 12:23
- 2 Be carefull with that, example: "2.10" < "2.2" – CoderPi Commented Jan 15, 2016 at 12:25
4 Answers
Reset to default 11No, you're not " able to pare version numbers correctly in JavaScript without having to split"
"2.2.8" > "2.2.10" // true
Those strings are pared character after character, from left to right.
You do need to split and pare number after number, which is easy enough. Here's for example how you could implement it:
function Version(s){
this.arr = s.split('.').map(Number);
}
Version.prototype.pareTo = function(v){
for (var i=0; ;i++) {
if (i>=v.arr.length) return i>=this.arr.length ? 0 : 1;
if (i>=this.arr.length) return -1;
var diff = this.arr[i]-v.arr[i]
if (diff) return diff>0 ? 1 : -1;
}
}
console.log((new Version("1.1.1")).pareTo(new Version("1.2.1"))); // -1
console.log((new Version("1.1.1")).pareTo(new Version("1.10.1"))); // -1
console.log((new Version("1.10.1.2")).pareTo(new Version("1.10.1"))); // 1
console.log((new Version("1.10.1.2")).pareTo(new Version("1.10.1.2"))); // 0
Because you're paring strings lexicographically, which yields the same result in your examples. However, this won't work in all circumstances, like when you get into double digits: 2.15.29
.
I know this is old and already have a marked answer, but the below code works pretty well for me using localeCompare
.
The function will return either:
0
: the version strings are equal1
: the versiona
is greater thanb
-1
: the versionb
is greater thana
function sort(a, b){ return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }) }
The above works for angularJS and Javascript. The localeCompare()
is an ES1 feature that is supported by all browsers.
For more detail on the usage refer to - https://www.w3schools./jsref/jsref_localepare.asp
better way to pare is to create a version number float and then a sub version number, like shown below
subVersion = parseInt(fullVersion.split(".")[2]);
mainVersion = parseFloat(fullOsVer);
after this conversion, you can do parison. this parison will be paring two integers.