Smooth Weighted Round-Robin Balancer

Distribute selections across weighted nodes with the smooth weighted round-robin algorithm, keeping interleaving fair without randomness.

TypescriptResilience

Code

typescriptsnippet
42 lines
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 === -1 short-circuits the flow with an early return when 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

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.