Created
August 12, 2022 14:58
-
-
Save jamesikanos/507272886f99a17e4c6f99e1d9e50b98 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const compare = (a, b) => { | |
// 1. Split by `.` | |
const splitA = a.split('.'); | |
const splitB = b.split('.'); | |
// 2. Inner Compare function for each conmponent | |
const _cmp = (an, bn) => (an < bn ? -1 : an > bn ? 1 : 0); | |
const maxLoop = Math.max(splitA.length, splitB.length); | |
// 3. Loop through component | |
for (let i = 0; i < maxLoop; i++) { | |
// 4. Compare the component | |
const r = _cmp(parseInt(splitA[i]), parseInt(splitB[i])); | |
// If not-equal, return the result (1 or -1) | |
if (r !== 0) { | |
return r; | |
} | |
} | |
// Return 0 if all components are equal | |
return 0; | |
}; | |
console.log(compare('2.0.0', '10.0.0')); | |
console.log(compare('1.3.1', '1.2.7')); | |
console.log(compare('1.0.0', '1.0.0')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment