DEV Community

Discussion on: JavaScript Katas: Higher Version

Collapse
 
pentacular profile image
pentacular

A little abstraction goes a long way to improving this answer.


const toVersion = (string) => string.split('.').map(Number);

const orderVersions = (v1, v2) => {
  for (let nth = 0; ; nth++) {
    if (v1[nth] === undefined && v2[nth] === undefined) {
      return 0;
    } else if (v1[nth] === undefined) {
     return -1;
    } else if (v2[nth] === undefined) {
      return 1;
    } else if (v1[nth] < v2[nth]) {
     return -1;
    } else if (v1[nth] > v2[nth]) {
      return 1;
    }
  }
}

const higherVersion = (string1, string2) =>
  orderVersions(toVersion(string1), toVersion(string2)) != -1;

console.log(higherVersion("1.2.3", "1.2.0"));
// true ✅

console.log(higherVersion("9", "10"));
// false ✅