Problems › TypeScript › network
Pick the next server in round-robin
A load balancer cycles through servers by index. Given the current slot and the total count, return the next one.
- The next server is (current + 1) modulo servers.
- When servers is zero or negative, return 0.
roundRobinNext(current: int, servers: int) → int
Where you start
function roundRobinNext(current: number, servers: number): number {
}
Worked examples
| Call | Result |
|---|---|
roundRobinNext(0, 5) | 1 |
roundRobinNext(4, 5) | 0 |
roundRobinNext(0, 1) | 0 |
roundRobinNext(3, 0) | 0 |
Hint
Modulo wraps the index back to zero.
Reference solution in TypeScript
function roundRobinNext(current: number, servers: number): number {
if (servers <= 0) return 0;
return (((current + 1) % servers) + servers) % servers;
}