Home > Javascript > Javascript version compare function

Javascript version compare function

Here’s quick javascript function for comparing versions. It works with any type of version strings, but it does not check for suffixes like ‘RC’, ‘alpha’, ‘stable’, etc. This was written in less than 10 minutes, so let me know if you find any bugs. Suggestions are welcomed anytime!

function versionCompare(a, b) {
	var A = a.split('.'), B = b.split('.'), ret = 0, base, sig, x, y;
	for(var i = 0, n = Math.max(A.length, B.length); i < n; i++) {
		x = 'undefined' == typeof A[i] ? 0 : parseInt(A[i]);
		y = 'undefined' == typeof B[i] ? 0 : parseInt(B[i]);
		
		base = Math.pow(10, n - i - 1);
		sig = 0;
		
		if( x < y ) { sig = -1; }
		else if( x > y ) { sig = 1; }
		
		ret += sig * base;
	}

	return ret == 0 ? 0 : ret / Math.abs(ret);
};
  1. No comments yet.
  1. No trackbacks yet.