Smooth Weighted Round-Robin Balancer
Distribute selections across weighted nodes with the smooth weighted round-robin algorithm, keeping interleaving fair without randomness.
Code
interface WeightedNode<T> {
value: T;
weight: number;
current: number;
}
export class SmoothWeightedRoundRobin<T> {
private readonly nodes: WeightedNode<T>[] = [];
private totalWeight = 0;
add(value: T, weight: number): this {
if (!Number.isInteger(weight) || weight < 1) {
throw new RangeError("weight must be a positive integer");
}
this.nodes.push({ value, weight, current: 0 });
this.totalWeight += weight;
return this;
}
remove(value: T): boolean {
const index = this.nodes.findIndex((node) => Object.is(node.value, value));
if (index === -1) return false;
this.totalWeight -= this.nodes[index].weight;
this.nodes.splice(index, 1);
return true;
}
next(): T {
if (this.nodes.length === 0) throw new Error("no nodes available");
let best = this.nodes[0];
for (const node of this.nodes) {
node.current += node.weight;
if (node.current > best.current) best = node;
}
best.current -= this.totalWeight;
return best.value;
}
get size(): number {
return this.nodes.length;
}
}How the snippet works
Smooth Weighted Round-Robin Balancer is built around the class SmoothWeightedRoundRobin.
Repetition is confined to for (const node of this.nodes) — the rest of the file is straight-line. A guard precedes the RangeError and Error: bad state stops the flow there instead of continuing.
What to watch for
- The guard
index === -1short-circuits the flow with an earlyreturnwhen its condition holds.
Using it
SmoothWeightedRoundRobin is the public entry point; everything else in the file exists to support it.
Key statements
const index = this.nodes.findIndex((node) => Object.is(node.value, value));
if (this.nodes.length === 0) throw new Error("no nodes available");
throw new RangeError("weight must be a positive integer");
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Bracket BalancerCheck whether parentheses, square brackets, and braces are balanced, reporting mismatches and maximum nesting depth.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does the snippet do with malformed data?
- `RangeError` and `Error` is raised at the guard (`index === -1`), so invalid state never reaches the main logic.
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything.
Report a problem with this exampleOpens a pre-filled issue on GitHub.