Checking versions numbers using Javascript

By Steve Claridge on 2014-03-15.

An interesting question popped up on Stackoverflow the other day: How to compare software version number using js? (only number). I think this would make a great interview question to get the interviewee writing some code, but maybe a bit harder than fizzbuzz.

Here's my solution, it assumes that the version numbers are passed as a comma-separated string and also assumes that all versions are numeric.

function f(txt) {
  this.toNum = function(n) {
    return parseInt(n,10);
  };   return txt.split(",").reduce( function(a,b) {
    var aa = a.split('.').map(this.toNum); //call .map to convert str to num
    var bb = b.split('.').map(this.toNum);
    for (var i=0; i < aa.length; i++) {
      if ( aa[i] == bb[i] )
        continue;
      if ( aa[i] > bb[i] )
        return a;
      else
        return b;       if (bb.length < i)
        return a;
    };          if (bb.length > aa.length)
      return b;
  });
}

Here's a jsFiddle to show it working.