Skip to content

Instantly share code, notes, and snippets.

@jamesikanos
Created August 12, 2022 14:58
Show Gist options
  • Save jamesikanos/507272886f99a17e4c6f99e1d9e50b98 to your computer and use it in GitHub Desktop.
Save jamesikanos/507272886f99a17e4c6f99e1d9e50b98 to your computer and use it in GitHub Desktop.
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