forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathos.js
More file actions
41 lines (33 loc) · 975 Bytes
/
os.js
File metadata and controls
41 lines (33 loc) · 975 Bytes
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
'use strict';
function getCIDRSuffix(mask, protocol = 'ipv4') {
const isV6 = protocol === 'ipv6';
const bitsString = mask
.split(isV6 ? ':' : '.')
.filter((v) => !!v)
.map((v) => pad(parseInt(v, isV6 ? 16 : 10).toString(2), isV6))
.join('');
if (isValidMask(bitsString)) {
return countOnes(bitsString);
} else {
return null;
}
}
function pad(binaryString, isV6) {
const groupLength = isV6 ? 16 : 8;
const binLen = binaryString.length;
return binLen < groupLength ?
`${'0'.repeat(groupLength - binLen)}${binaryString}` : binaryString;
}
function isValidMask(bitsString) {
const firstIndexOfZero = bitsString.indexOf(0);
const lastIndexOfOne = bitsString.lastIndexOf(1);
return firstIndexOfZero < 0 || firstIndexOfZero > lastIndexOfOne;
}
function countOnes(bitsString) {
return bitsString
.split('')
.reduce((acc, bit) => acc += parseInt(bit, 10), 0);
}
module.exports = {
getCIDRSuffix
};