None of these answers are optimal for the following reasons:
- Your passed parameters can be strings. later you convert them to an array. it's expensive and goes against good coding practice. NEVER change the type of a variable after it is initialized! Create a new variable to store the array.
- A function continues through the loop even after it has enough information to return with the result.
Basically, you want to start with the main version and work up to the younger version. Once you find one that is not equal, you want to return. It is standard when performing a function (a, b) that is greater than the operation that the return value of the function should be:
1 = a > b -1 = a < b 0 = a===b
Otherwise, anyone calling this function will not know why it returns true, unless it looks at its internal elements. If it is reduced and confused, it can be a waste of time.
I rewrote and improved the function with this in mind.
function (versionA, versionB) { var arrA, arrB; arrA = typeof versionA !== 'object' ? versionA.toString().split('.') : versionA; arrB = typeof versionB !== 'object' ? versionB.toString().split('.') : versionB; for (var i = 0; i < (Math.max(arrA.length, arrB.length)); i++) { arrA[i] = typeof arrA[i] === 'undefined' ? 0 : Number(arrA[i]); arrB[i] = typeof arrB[i] === 'undefined' ? 0 : Number(arrB[i]); if (arrA[i] > arrB[i]) { return 1; } if (arrA[i] < arrB[i]) { return -1; } } return 0; };
source share