All files / server/tests/helpers port.js

84.62% Statements 11/13
60% Branches 3/5
100% Functions 2/2
83.33% Lines 10/12
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      9x 9x   51x     9x     51x       51x     51x         51x 51x     9x  
// Port - generate a random valid port number that has not been used yet
 
// Get an unused port in the user range (2000 - 10000)
const ports = [];
const limit = 1000;
 
const random = () => 2000 + parseInt(Math.random() * 8000);
 
// Keep a count of how many times we tried to find a port to avoid infinite loop
const randPort = (i = 0) => {
 
  // Too many ports tried and none was available
  Iif (i >= limit) {
    throw new Error('Tried to find a port but none seems available');
  }
 
  const port = random();
 
  // If "i" is already taken try again
  Iif (port in ports) {
    return randPort(i + 1);
  }
 
  // Add it to the list of ports already being used and return it
  ports.push(port);
  return port;
}
 
module.exports = randPort;