Friday, May 25, 2012

JavaScript Function to Compare Versions

Useful to compare version numbers, e.g., Flash Player versions.

Only work with digital versions.

Live demo: jsfiddle example

function compVersions(strV1, strV2) {
  var nRes = 0
    , parts1 = strV1.split('.')
    , parts2 = strV2.split('.')
    , nLen = Math.max(parts1.length, parts2.length);

  for (var i = 0; i < nLen; i++) {
    var nP1 = (i < parts1.length) ? parseInt(parts1[i], 10) : 0
      , nP2 = (i < parts2.length) ? parseInt(parts2[i], 10) : 0;

    if (isNaN(nP1)) { nP1 = 0; }
    if (isNaN(nP2)) { nP2 = 0; }

    if (nP1 != nP2) {
      nRes = (nP1 > nP2) ? 1 : -1;
      break;
    }
  }

  return nRes;
};

alert(compVersions('10', '10.0')); // 0
alert(compVersions('10.1', '10.01.0')); // 0
alert(compVersions('10.0.1', '10.0')); // 1
alert(compVersions('10.0.1', '10.1')); // -1