Advertisement
Guova

IP address autocomplete

Sep 20th, 2020
1,372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class IP {
  2.  
  3.     ipAddressAutocomplete(input = '') {
  4.         if (input === null) return '';
  5.         input = input.toString();
  6.         let ipArray = input.split('.');
  7.         const numberOnTheRight = ipArray[ipArray.length - 1];
  8.         let exceptNumberOnRight = '';
  9.         let remainder = '';
  10.         for (let i = 0; i < 3; i ++) {
  11.             exceptNumberOnRight += (i <= ipArray.length - 2) ? ipArray[i] : '';
  12.             exceptNumberOnRight += (i <= ipArray.length - 2) ? '.' : '';
  13.  
  14.             remainder += (i >= ipArray.length - 1) ? '.0-255' : '';
  15.         }
  16.        
  17.         const possibilities = this.expectedNotationRange(numberOnTheRight);
  18.         let rawOutput = [];
  19.         for (let i = 0; i < possibilities.length; i ++) {
  20.             rawOutput.push(exceptNumberOnRight + possibilities[i] + remainder);
  21.         }
  22.  
  23.         return rawOutput.join(', ');
  24.     }
  25.  
  26.     expectedNotationRange (input = 0) {
  27.         if (input === null) return ['0-255'];
  28.         if (input === 0) return ['0'];
  29.         let stringInput = input.toString();
  30.         let possibleNumbers = [stringInput];
  31.         for (let i = 0; i < 3; i ++) {
  32.             if (stringInput.length < 3) {
  33.                 stringInput += '0';
  34.                 if (parseFloat(stringInput) < 255) {
  35.                     possibleNumbers.push(stringInput);
  36.                 }
  37.             }
  38.         }
  39.         possibleNumbers.forEach((number, index) => {
  40.             if (index > 0) {
  41.                 const originalNumber = number;
  42.                 let add = '0';
  43.                 for (let a = 0; a < number.split("0").length - 1; a ++) {
  44.                     add += '9';
  45.                 }
  46.                 console.log('add = '+parseFloat(add));
  47.                 let maxNum = originalNumber + Math.min(parseFloat(number) + parseFloat(add), 255).toString();
  48.                 possibleNumbers[index] = `${number}-${maxNum.slice(number.length)}`;
  49.             }
  50.         });
  51.         return possibleNumbers;
  52.     }
  53. }
  54.  
  55. module.exports = IP;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement