DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 80

The task is to implement a function that compares two semvar strings.

The boilerplate code

function compare(v1, v2) {
  // your code here
}

Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Compare numbers one position at a time

for(let i = 0; i < len; i++) {
    const x = a[i] || 0;
    const y = b[i] || 0;
  }
Enter fullscreen mode Exit fullscreen mode

If there are no numbers, it defaults to 0. If version 1 is bigger than version 2, return 1

if(x > y) return 1;
Enter fullscreen mode Exit fullscreen mode

If version 2 is bigger, return -1

if(x < y) return -1;
Enter fullscreen mode Exit fullscreen mode

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;
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)