The task is to implement a function that compares two semvar strings.
The boilerplate code
function compare(v1, v2) {
// your code here
}
Semvar stands for semantic versioning, and a semvar string looks like this: '2.0.0'. They are used to indicate versions of packages.
Split each version into numbers
const a = v1.split('.').map(Number);
const b = v2.split('.').map(Number);
Compare numbers one position at a time
for(let i = 0; i < len; i++) {
const x = a[i] || 0;
const y = b[i] || 0;
}
If there are no numbers, it defaults to 0. If version 1 is bigger than version 2, return 1
if(x > y) return 1;
If version 2 is bigger, return -1
if(x < y) return -1;
The final code
function compare(v1, v2) {
// your code here
const a = v1.split('.').map(Number);
const b = v2.split('.').map(Number);
const len = Math.max(a.length, b.length);
for(let i = 0; i < len; i++) {
const x = a[i] || 0;
const y = b[i] || 0;
if(x > y) return 1;
if(x < y) return -1;
}
return 0;
}
That's all folks!
Top comments (0)