Count IP Addresses (5 kyu): Codewars (TDD in JavaScript)
Jan 27, 2020 08:00 · 522 words · 3 minute read
Hi! Welcome to Codewars. In this series I’m going to solve TDD katas using JavaScript. If this is your first time here and you want to learn Frontend and JavaScript, start right now by subscribing, and don’t forget to turn on the subtitles. [Music playing] Let’s solve today kata titled “Count IP Addresses.” Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one). Okay. All inputs will be valid IPv4 addresses in the form of strings.
00:40 - The last address will always be greater than the first one. So I don’t need to check this boundaries, okay. Let’s consider an example. The start and the end, the different between them is to 256, okay. In the one place there are 255 IP addresses. In the first one there are 255, but in the second one there are 255 times 255. The third - 255 times 255 times 255, okay. And for this case, there are 255 plus 1, is 256, okay. Let’s consider these two cases. The first one. There is the difference in 50 IP addresses. For the second case it’s more interesting. There are 256, as we see in the previous case, but the start address is 10. So the result is 256 - 10 = 246. So to solve kata I have to do the following.
01:46 - I need to calculate the difference between each place of this range from start to end and multiply the result by the value of each place. I need to split the string by “dot,” thus I’ll get the value of each place, calculate the difference and then get the sum of these results. Let’s calculate these digits. First one should be… And split. And take third element. Then “start,” split by “dot,” and take third element. And let’s do the same for all digits. Second one. Second, first, zero. It will be here “third”. Here - “fourth.” Let’s review them. Yes, as expected. Here we have 1 and -10. This one should be multiplied by 256 and -10. So, let’s create a helper function for that. It will be like this.
03:18 - “Calc” function that takes a value and a place of this IP address. For the default value it should be 1, just for simplification. And returns “end” address, split by “dot” “n-th” position minus start. Times “m”. Let’s review our function here. Let’s try. That’s correct. And now we can provide the final result. For that I don’t need these temporary variables. And return the value. According to each place I need to add its multiplication factor, like this. Plus the next value. Plus the last one. Let’s try this. And for all test cases. Yes, that’s correct. I like it. My code is available on GitHub.
04:45 - Documentation is available in the Internet. Follow the links if you’re eager to get more. If you like this video give it “thumbs up”, share it with your friends, subscribe to the channel and watch other episodes. Thanks for watching and dive deeper. .