JSFiddle - React, Tailwind, and code Playground

by Luis Perez

JavaScript

const vers = ['0.1.1.3', '0.1.3.3', '0.1.1.30'];

/**
 * @description - Given two versions will return 1 if a > b, 0 if a === b, and -1 if a < b
 * Expected format for the versions is 'x.x.x.x'
 * @param {string} a
 * @param {string} b
 * @return {number}
 * @constructor
 */
export function CompareVersions(a, b) {
  const [A, B] = [a.split('.'), b.split('.')];
  let result = 0;

  A.some((tag, idx) => {
    const a_tag = +tag;
    const b_tag = B && +B[idx];
    let found = true;

    if (b_tag == null || a_tag == null) {
      /**
       * If the b value does not have a valid tag will exit out, and short circuit the some.
       * Catch the end of input found
       **/
    } else if (a_tag > b_tag) {
      result = 1;
    } else if (a_tag < b_tag) {
      result = -1;
    } else {
      found = false;
    }
    return found;
  });
  return result;
}


console.log(CompareVersion('0.1.1', '0.1'));