Created
November 7, 2023 08:38
-
-
Save p0rsche/871b30712d5fc859d5e323d3e300bb4a 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 assert = require('node:assert'); | |
const parseInt = (n) => Number.parseInt(n) | |
function versionComparator(v1, v2) { | |
const v1arr = v1.split('.').map(parseInt); | |
const v1arrlen = v1arr.length; | |
const v2arr = v2.split('.').map(parseInt); | |
const v2arrlen = v2arr.length; | |
// preventing out of bounds | |
const len = v1arrlen > v2arrlen ? v2arrlen : v1arrlen; | |
for(let i = 0; i < len; i++) { | |
if (v1arr[i] === v2arr[i]) { | |
continue; | |
} | |
return v1arr[i] > v2arr[i] ? 1 : -1; | |
} | |
return 0 | |
} | |
const versions = [ | |
['1.0.1', '1.0.01', 0], | |
['1.0.1', '0.1.0.1.0', 1], | |
['1.0.2', '1.0.0.2', 1], | |
['2.1.0', '2.4.6.001', -1], | |
] | |
versions.forEach(([v1, v2, answer]) => { | |
const result = versionComparator(v1, v2); | |
console.log(v1, v2, result); | |
assert.equal(result, answer) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment