DEV Community

Cover image for JavaScript Katas: Higher Version
miku86
miku86

Posted on

JavaScript Katas: Higher Version

Intro 🌐

Problem solving is an important skill, for your career and your life in general.

That's why I take interesting katas of all levels, customize them and explain how to solve them.


Understanding the Exercise❗

First, we need to understand the exercise!
If you don't understand it, you can't solve it!.

My personal method:

  1. Input: What do I put in?
  2. Output: What do I want to get out?

Today's exercise

Today, another 7 kyu kata,
meaning we slightly increase the difficulty.

Source: Codewars

Write a function higherVersion, that accepts two parameters: version1 and version2.

Given two strings, e.g. "1.2.3" and "1.2.0", return if the first string is higher than the second, e.g. true.

There are no leading zeros, e.g. 100.020.003 is given as 100.20.3.


Input: two strings.

Output: a boolean.


Thinking about the Solution πŸ’­

I think I understand the exercise (= what I put into the function and what I want to get out of it).

Now, I need the specific steps to get from input to output.

I try to do this in small baby steps:

  1. Check if the current number of the first string is higher, lower or equal than/to the first number of the second string
  2. If higher, then return true
  3. If lower, then return false
  4. If equal, go to the next number of both strings and start from step 1

Example:

  • Input: "1.2.3", "1.2.0"
  • Check if the current number of the first string is higher, lower or equal than/to the first number of the second string: 1 and 1 => equal
  • If equal, go to the next number of both strings and start from step 1
  • Check if the second number of the first string is higher, lower or equal than/to the second number of the second string: 2 and 2 => equal
  • If equal, go to the next number of both strings and start from step 1
  • Check if the third number of the first string is higher, lower or equal than/to the third number of the second string: 3 and 0 => higher
  • If higher, then return true
  • Output: true βœ…

Implementation β›‘

function higherVersion(version1, version2) {
  // split the strings into numbers
  const split1 = version1.split(".").map((s) => Number(s));
  const split2 = version2.split(".").map((s) => Number(s));
  let result = null;

  for (let i = 0; i < split1.length; i++) {
    if (split1[i] > split2[i]) {
      // is higher, so break out of the whole loop
      result = true;
      break;
    } else if (split1[i] < split2[i]) {
      // is smaller, so break out of the whole loop
      result = false;
      break;
    } else {
      // is equal, so check the next number
      result = false;
    }
  }

  return result;
}
Enter fullscreen mode Exit fullscreen mode

Result

console.log(higherVersion("1.2.3", "1.2.0"));
// true βœ…

console.log(higherVersion("9", "10"));
// false βœ…
Enter fullscreen mode Exit fullscreen mode

Playground ⚽

You can play around with the code here


Next Part ➑️

Great work!

We learned how to use split, map, for, break.

I hope you can use your new learnings to solve problems more easily!

Next time, we'll solve another interesting kata. Stay tuned!


If I should solve a specific kata, shoot me a message here.

If you want to read my latest stuff, get in touch with me!


Further Reading πŸ“–


Questions ❔

  • How often do you do katas?
  • Which implementation do you like more? Why?
  • Any alternative solution?

Top comments (9)

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 βœ…
Collapse
 
westim profile image
Tim West

I appreciate the desire for a single exit point, but seems unnecessary in this situation.

Here's a version that's much easier to read based on the CodeWars discussion with the additional feature of handling mismatched lengths:

function higherVersion(ver1, ver2) {
    ver1 = ver1.split('.').map(Number);
    ver2 = ver2.split('.').map(Number);
    const limit = Math.min(ver1.length, ver2.length);
    for (let i = 0; i < limit; i++)
        if (ver1[i] !== ver2[i])
            return ver1[i] > ver2[i];

    return ver1.length > ver2.length;  
}
Collapse
 
rambou profile image
Nikolaos Bousios

But this is faster and simpler right?

function higherVersion(version1, version2) {
  // split the strings into numbers
  const split1 = version1.split('.').join('');
  const split2 = version2.split('.').join('');

  return Number(split1) > Number(split2);
}

// TEST CASES
const testInput01 = ["1.2.3", "1.2.0"]; // true
const testInput02 = ["9", "10"]; // false

// OUTPUT
console.log("--------------");
console.log(higherVersion(testInput01[0], testInput01[1]));
console.log(higherVersion(testInput02[0], testInput02[1]));
console.log("----------------------------");
Collapse
 
westim profile image
Tim West

With the assumption that the two versions are the same length and have no leading zeros, yes. I'd probably recommend .replaceAll('.', '') over split('.').join('').

Collapse
 
gerges27 profile image
Gerges Nady

let stringOne = Number(v1.split(".").join(""))
let stringTwo = Number(v2.split(".").join(""))

if (stringOne > stringTwo) {
    return console.log("true")
} else if (stringOne < stringTwo) {
    return console.log("false")
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pentacular profile image
pentacular

Adjust the partition if you want to exclude the equal case.

const higherVersion = (string1, string2) =>
  orderVersions(toVersion(string1), toVersion(string2)) > 0;
Collapse
 
totally_chase profile image
Phantz • Edited

would Number(version1.split('.').join('')) > Number(version2.split('.').join('')) be enough or are there cases where it doesn't work?

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ • Edited
higherVersion=(a,b)=>(c=v=>v.split('.').reduce((f,s)=>f+=s.padStart(9,'0'),''),c(a)>c(b))
 
pentacular profile image
pentacular

The nice thing is that it should also allow you to sort an arbitrary number of versions.