Skip to content

Instantly share code, notes, and snippets.

@kerrishotts
Created August 3, 2019 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerrishotts/797450a10a8a4218f36a210b50ff5ba9 to your computer and use it in GitHub Desktop.
Save kerrishotts/797450a10a8a4218f36a210b50ff5ba9 to your computer and use it in GitHub Desktop.
Dev.to 2019-08-03 Daily Challenge: # of valid IPs in a given range
/**
* Converts an IP String to its integer representation
*
* @param ipString {string} An IP Address in the form a.b.c.d
* @return {number} The integer representation of the IP address
*/
const convertIPStringToNumber = ipString => ipString.split(".")
.reduce((acc, part) => (acc << 8) | Number(part), 0);
/**
* Calculates the number of IP address between start and finish, not inclusive
* of finish.
*
* @param start {string} An IP Address of the form a.b.c.d
* @param finish {string} An IP address of the form a.b.c.d
* @returns {number} The number of IP addresses, not inclusive of the last one.
*/
const ipsBetween = (start, finish) => Math.abs(convertIPStringToNumber(finish) - convertIPStringToNumber(start));
const assert = (exprFn, expected, msg) => {
const actual = exprFn();
if (actual !== expected) {
throw new Error(`${msg}; expected ${expected} got ${actual}`);
}
};
assert(() => convertIPStringToNumber("0.0.0.0"), 0, "Ensure a zero IP is 0");
assert(() => convertIPStringToNumber("0.0.0.1"), 1, "Ensure a one in the last part is 1");
assert(() => convertIPStringToNumber("0.0.1.0"), 256, "Ensure a one in the third part is 256");
assert(() => convertIPStringToNumber("0.0.1.1"), 257, "Ensure a one in the last two parts is 257");
assert(() => ipsBetween("10.0.0.0", "10.0.0.50"), 50, "Ensure there are fifty valid addresses");
assert(() => ipsBetween("10.0.0.0", "10.0.1.0"), 256, "Ensure there are 256 valid addresses");
assert(() => ipsBetween("10.0.1.0", "10.0.0.0"), 256, "Ensure there are 256 valid addresses");
assert(() => ipsBetween("20.0.0.10", "20.0.1.0"), 246, "Ensure there are 246 valid addresses");
assert(() => ipsBetween("192.168.1.1", "192.168.1.5"), 4, "Ensure there are 4 valid addresses");
assert(() => ipsBetween("192.168.1.1", "192.168.1.1"), 0, "Ensure there are 0 valid addresses");
assert(() => ipsBetween("192.168.1.0", "192.168.1.1"), 1, "Ensure there are 1 valid addresses");
assert(() => ipsBetween("192.168.1.1", "192.168.1.0"), 1, "Ensure there are 1 valid addresses, accounting for negative order");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment