Islombe dev
69 subscribers
118 photos
26 videos
80 links
Here I share thoughts, news, memes.
Topic: IT and more :)

My website: https://islombe-dev.uz

My soc. networks:
- youtube.com/@islombe_dev
- instagram.com/islombe_dev
Download Telegram
Don't Overthink, Start Solving! 💡

When faced with a complex task, it's easy to overthink and get lost in endless solutions. But here's the key: just start solving!

Once you get the correct result, it's time to optimize.
Bit by bit, refine your code—make it more readable, maintainable, and sometimes even faster (but not always 😉).

Here is an example:

Task is
Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).

All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one.


Solution optimizing evolution

First version, which works, but its a big unreadable code
// first version
export function ipsBetweenV1(start: string, end: string): number {
const reversedStart = start
.split(".")
.reverse()
.map((segment) => parseInt(segment, 10)) as number[]
const reversedEnd = end
.split(".")
.reverse()
.map((segment) => parseInt(segment, 10)) as number[]

const amountInStart = reversedStart.reduce((acc, curr, index) => {
acc += curr * Math.pow(256, index) + 1
return acc
})
const amountInEnd = reversedEnd.reduce((acc, curr, index) => {
acc += curr * Math.pow(256, index) + 1
return acc
})

return amountInEnd - amountInStart
}

Nasty...

Implementing DRY and Divide-and-conquer:
// second version
export function ipsBetweenV2(start: string, end: string): number {
const getReversedSegments = (ip: string) => {
return ip
.split(".")
.reverse()
.map((segment) => parseInt(segment, 10)) as number[]
}
const calcAmountInIps = (ips: string) => {
return getReversedSegments(ips).reduce((acc, curr, index) => {
acc += curr * Math.pow(256, index) + 1
return acc
}) as number
}

return calcAmountInIps(end) - calcAmountInIps(start)
}

Looks much better. But something is missing, and looks like we overdoing something...

Removing unneeded reverse(), and simplifying functions into one with readable structure:
export function ipsBetween(start: string, end: string): number {
const ipToNumber = (ip: string): number =>
ip.split(".").reduce((acc, curr, index) => acc * 256 + parseInt(curr, 10), 0);

return ipToNumber(end) - ipToNumber(start);
}

Final solution looks 10 times better, much more readable and well structured 🗣

#CodingTips #ProblemSolving #DeveloperLife
Please open Telegram to view this post
VIEW IN TELEGRAM
31