Skip to content

Commit

Permalink
fix: explicit port/portRange even if randon is true
Browse files Browse the repository at this point in the history
  • Loading branch information
peterroe committed Oct 22, 2023
1 parent 9091db5 commit 45f71c6
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
13 changes: 12 additions & 1 deletion src/_internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,25 @@ export function _log(verbose: boolean, message: string) {
}
}

export function _generateRange(from: number, to: number): number[] {
export function _generateRange(
range: [from: number, to: number],
random?: boolean,
): number[] {
const [from, to] = range;
if (to < from) {
return [];
}
const r = [];
for (let index = from; index < to; index++) {
r.push(index);
}
// Fisher-Yates shuffle algorithm
if (random) {
for (let i = r.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[r[i], r[j]] = [r[j], r[i]];
}
}
return r;
}

Expand Down
9 changes: 4 additions & 5 deletions src/get-port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,14 @@ export async function getPort(
),
} as GetPortOptions;

if (options.random) {
if (options.random && options.portRange.length === 0 as number) {
return getRandomPort(options.host);
}

// Generate list of ports to check
const portsToCheck: PortNumber[] = [
options.port,
...options.ports,
..._generateRange(...options.portRange),
...(options.random ? [] : [options.port, ...options.ports]),
..._generateRange(options.portRange, options.random)
].filter((port) => {
if (!port) {
return false;
Expand All @@ -70,7 +69,7 @@ export async function getPort(
// Try fallback port range
if (!availablePort && options.alternativePortRange.length > 0) {
availablePort = await _findPort(
_generateRange(...options.alternativePortRange),
_generateRange(options.alternativePortRange),
options.host,
);
_log(
Expand Down

0 comments on commit 45f71c6

Please sign in to comment.