Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assign unused subnet automatically #418

Merged
merged 6 commits into from
May 19, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
use least used subnet
  • Loading branch information
sinamics committed May 19, 2024
commit 720b22ec92aaff82d2f0e89ded2cec43a5a75f93
32 changes: 28 additions & 4 deletions src/utils/IPv4gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,40 @@ const cidrOptions = [
"172.25.30.0/24",
];

// const generateCidr = () => {
// return cidrOptions[Math.floor(Math.random() * cidrOptions.length)];
// };
const generateCidr = (usedCidr: string[][]) => {
// Flatten the usedCidr array
const flattenedUsedCidr = usedCidr.flat();

// Count the frequency of each CIDR in the usedCidr array
const cidrFrequency: { [key: string]: number } = {};
for (const cidr of flattenedUsedCidr) {
if (cidrFrequency[cidr]) {
cidrFrequency[cidr]++;
} else {
cidrFrequency[cidr] = 1;
}
}

// Filter the available CIDRs
const availableCidr = cidrOptions.filter((cidr) => !flattenedUsedCidr.includes(cidr));
return availableCidr.length > 0 ? availableCidr[0] : cidrOptions[0];

// If there are available CIDRs, return the first one
if (availableCidr.length > 0) {
return availableCidr[0];
}

// If no available CIDRs, find the CIDR with the fewest occurrences
let leastUsedCidr = cidrOptions[0];
let minCount = Infinity;
for (const cidr of cidrOptions) {
const count = cidrFrequency[cidr] || 0;
if (count < minCount) {
minCount = count;
leastUsedCidr = cidr;
}
}

return leastUsedCidr;
};
export const IPv4gen = (CIDR: string | null, usedCidr) => {
const cidr = CIDR ? CIDR : generateCidr(usedCidr);
Expand Down
Loading