Created
January 19, 2024 21:51
-
-
Save AimeeKnight/5b8e883397c9ca65af3cde1530112124 to your computer and use it in GitHub Desktop.
ip-cider.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ipToNumber = (ip) => ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); | |
const findConsecutiveIPs = (ips) => { | |
ips.sort((a, b) => ipToNumber(a) - ipToNumber(b)); | |
const result = []; | |
let startIP = ips[0]; | |
let endIP = ips[0]; | |
for (let i = 1; i < ips.length; i++) { | |
const currentIP = ips[i]; | |
const expectedNextIP = ipToNumber(endIP) + 1; | |
if (ipToNumber(currentIP) === expectedNextIP) { | |
endIP = currentIP; | |
} else { | |
result.push(startIP === endIP ? startIP : `${startIP}-${endIP}`); | |
startIP = endIP = currentIP; | |
} | |
} | |
result.push(startIP === endIP ? startIP : `${startIP}-${endIP}`); | |
return result; | |
}; | |
const consecutiveIPs = [ | |
'192.168.1.1', | |
'192.168.1.2', | |
'192.168.1.3', | |
'192.168.1.5', | |
'192.168.1.6', | |
'192.168.1.8', | |
]; | |
const summarizedCIDRs = findConsecutiveIPs(consecutiveIPs); | |
console.log(summarizedCIDRs); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment