-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path5-kyu-count-ip-addresses.js
75 lines (61 loc) · 2.51 KB
/
5-kyu-count-ip-addresses.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// 5 kyu | Count IP Addresses
// https://www.codewars.com/kata/526989a41034285187000de4
/*
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.
## Examples
```
ipsBetween("10.0.0.0", "10.0.0.50") === 50
ipsBetween("10.0.0.0", "10.0.1.0") === 256
ipsBetween("20.0.0.10", "20.0.1.0") === 246
```
*/
// 〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰
// You have passed all of the tests! :)
// const ipsBetween = (start, end) => {
// // console.log(start, end);
// // console.log([start, end].map(ip => ip.split('.').map(Number)));
// const [splitS, splitE] = [start, end].map(ip => ip.split('.').map(Number));
// // console.log(splitS, splitE);
// // let tmp = 256;
// // console.log(
// // splitS.map((n, i) => n * 256 ** (3 - i)).reduce((acc, curr) => acc + curr),
// // );
// // console.log(
// // splitE.map((n, i) => n * 256 ** (3 - i)).reduce((acc, curr) => acc + curr),
// // );
// // console.log(
// // splitE.map((n, i) => n * 256 ** (3 - i)).reduce((acc, curr) => acc + curr) -
// // splitS
// // .map((n, i) => n * 256 ** (3 - i))
// // .reduce((acc, curr) => acc + curr),
// // );
// return (
// splitE.map((n, i) => n * 256 ** (3 - i)).reduce((acc, curr) => acc + curr) -
// splitS.map((n, i) => n * 256 ** (3 - i)).reduce((acc, curr) => acc + curr)
// );
// // console.log([256 ** 4, 256 ** 3, 256 ** 2, 256 ** 1]);
// // const difference = splitE.map((n, i) => n - splitS[i]);
// // console.log(difference);
// };
// 〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰
/**
* @param {string} start
* @param {string} end
* @returns {number}
*/
const ipsBetween = (start, end) =>
[start, end]
.map(ip =>
ip
.split('.')
.reduce((sum, bits, idx) => sum + Number(bits) * 256 ** (3 - idx), 0),
)
.reduce((s, e) => e - s);
// 〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰〰
import { strictEqual } from 'assert';
strictEqual(ipsBetween('10.0.0.0', '10.0.0.50'), 50);
strictEqual(ipsBetween('10.0.0.10', '10.0.1.0'), 246);
strictEqual(ipsBetween('20.0.0.10', '20.0.1.0'), 246);