This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
157. semver compare
Here's one possible solution using basic string manipulation and comparison:
function compare(version1, version2) {
const parts1 = version1.split('.');
const parts2 = version2.split('.');
for (let i = 0; i < 3; i++) {
const num1 = parseInt(parts1[i]);
const num2 = parseInt(parts2[i]);
if (num1 > num2) {
return 1;
} else if (num1 < num2) {
return -1;
}
}
return 0;
}
Explanation:
- The function takes in two semver strings,
version1
andversion2
. - Each semver string is split into an array
parts
based on the period separator. - For each part (up to the third), it is converted to an integer using
parseInt()
. - If the current part of
version1
is greater than that ofversion2
, we return1
. - If the current part of
version1
is less than that ofversion2
, we return-1
. - If we reach the end of the loop without returning, it means the two versions are equal, so we return
0
.