UNPKG

2.94 kBJavaScriptView Raw
1import binary from './binary.js'
2
3export default class IP {
4 #octetOne;
5 #octetTwo;
6 #octetThree;
7 #octetFour;
8
9 constructor(ipString) {
10 const octetArray = this.#arrayFromString(ipString)
11 if (typeof octetArray[0] === 'undefined') {
12 throw new Error('Incorrect arguments for IP. Expected a String like 127.0.0.1')
13 }
14 if (typeof octetArray[1] === 'undefined') {
15 throw new Error('Incorrect arguments for IP. Expected a String like 127.0.0.1')
16 }
17 if (typeof octetArray[2] === 'undefined') {
18 throw new Error('Incorrect arguments for IP. Expected a String like 127.0.0.1')
19 }
20 if (typeof octetArray[3] === 'undefined') {
21 throw new Error('Incorrect arguments for IP. Expected a String like 127.0.0.1')
22 }
23 this.#octetOne = octetArray[0]
24 this.#octetTwo = octetArray[1]
25 this.#octetThree = octetArray[2]
26 this.#octetFour = octetArray[3]
27 }
28
29 asBinaryArray = () => {
30 let binaryAddress = []
31
32 binaryAddress.push(binary.octetToBinary(this.#octetOne))
33 binaryAddress.push(binary.octetToBinary(this.#octetTwo))
34 binaryAddress.push(binary.octetToBinary(this.#octetThree))
35 binaryAddress.push(binary.octetToBinary(this.#octetFour))
36
37 return binaryAddress
38 }
39
40 asDecimalArray = () => {
41 let decimalAddress = []
42
43 decimalAddress.push(Number(this.#octetOne))
44 decimalAddress.push(Number(this.#octetTwo))
45 decimalAddress.push(Number(this.#octetThree))
46 decimalAddress.push(Number(this.#octetFour))
47
48 return decimalAddress
49 }
50
51 #arrayFromString = (ipAsString) => {
52 return ipAsString.split('.')
53 }
54
55 static fromBinaryOctetArray = (octetArray) => {
56 let hostIP = ''
57 for (let i = 0; i < octetArray.length; i++) {
58 if (i !== 0) hostIP += '.'
59 hostIP += binary.octetToDecimal(octetArray[i])
60 }
61 return new IP(hostIP)
62 }
63
64 static isSyntaxValid = (ipAsString) => {
65 const ipAsArray = ipAsString.split('.')
66 if (ipAsArray.length !== 4) return false
67 else if (ipAsArray[0] < 0 || ipAsArray[1] > 255) return false
68 else if (ipAsArray[1] < 0 || ipAsArray[1] > 255) return false
69 else if (ipAsArray[2] < 0 || ipAsArray[2] > 255) return false
70 else if (ipAsArray[3] < 0 || ipAsArray[3] > 255) return false
71 else return true
72 }
73
74 toString() {
75 return `${this.#octetOne}.${this.#octetTwo}.${this.#octetThree}.${this.#octetFour}`
76 }
77
78 get octetOne() {
79 return this.#octetOne
80 }
81
82 get octetTwo() {
83 return this.#octetTwo
84 }
85
86 get octetThree() {
87 return this.#octetThree
88 }
89
90 get octetFour() {
91 return this.#octetFour
92 }
93
94}
\No newline at end of file