From 8b98321b9c8e829ea6a9470ab403e36639f3ae8b Mon Sep 17 00:00:00 2001 From: Steven Evans Date: Wed, 4 Jul 2018 21:04:00 -0400 Subject: [PATCH] [refactor] Moved `getRandombyte` to its own TS file Also made use of `getRandomInt` --- utils/IPAddress.js | 14 ++++++-------- utils/helpers/getRandomByte.ts | 13 +++++++++++++ 2 files changed, 19 insertions(+), 8 deletions(-) create mode 100644 utils/helpers/getRandomByte.ts diff --git a/utils/IPAddress.js b/utils/IPAddress.js index 90719d70c..1a955472a 100644 --- a/utils/IPAddress.js +++ b/utils/IPAddress.js @@ -1,13 +1,15 @@ import {AllServers} from "../src/Server"; +import {getRandomByte} from "./helpers/getRandomByte"; + /* Functions to deal with manipulating IP addresses*/ //Generate a random IP address //Will not return an IP address that already exists in the AllServers array function createRandomIp() { - var ip = createRandomByte(99) +'.' + - createRandomByte(9) +'.' + - createRandomByte(9) +'.' + - createRandomByte(9); + var ip = getRandomByte(99) + '.' + + getRandomByte(9) + '.' + + getRandomByte(9) + '.' + + getRandomByte(9); //If the Ip already exists, recurse to create a new one if (ipExists(ip)) { @@ -28,10 +30,6 @@ function ipExists(ip) { return false; } -function createRandomByte(n=9) { - return Math.round(Math.random()*n); -} - function isValidIPAddress(ipaddress) { if (/^(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-6]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) { diff --git a/utils/helpers/getRandomByte.ts b/utils/helpers/getRandomByte.ts new file mode 100644 index 000000000..5b6ddf57d --- /dev/null +++ b/utils/helpers/getRandomByte.ts @@ -0,0 +1,13 @@ +import { getRandomInt } from "./getRandomInt"; + +/** + * Gets a random value in the range of a byte (0 - 255), or up to the maximum. + * @param max The maximum value (up to 255). + */ +export function getRandomByte(max: number) { + // Technically 2^8 is 256, but the values are 0-255, not 1-256. + const byteMaximum: number = 255; + const upper: number = Math.max(Math.min(max, byteMaximum), 0); + + return getRandomInt(0, upper); +}