Picker that cycles values in turn with peek and reset
A support desk assigns incoming chats to agents in turn: the first chat goes to the first agent, the next to the second, and after the last agent it starts over. The dashboard also shows who gets the next chat, and a manager can restart the rotation at the beginning of a shift.
Implement roundRobin(...values). It returns a picker: a function that returns the next value in turn each time you call it.
const next = roundRobin(...values);
next(); // => the next value, wrapping around after the last one
next.peek(); // => the value next() would return, without advancing
next.reset(); // start over from the first value
next.peek() returns the value the next call to next() will return. It does not move the picker.next.reset() moves the picker back to the first value. It returns undefined.next() and next.peek() always return undefined.0, '', null and undefined.roundRobin creates an independent picker.roundRobin(...agents) and then changing the agents array must not change the picker.const nextAgent = roundRobin('Maya', 'Leo', 'Priya');
nextAgent(); // => 'Maya'
nextAgent(); // => 'Leo'
nextAgent.peek(); // => 'Priya'
nextAgent(); // => 'Priya'
nextAgent(); // => 'Maya'
nextAgent.reset();
nextAgent(); // => 'Maya'
const nextLight = roundRobin('green');
nextLight(); // => 'green'
nextLight(); // => 'green'
roundRobin()(); // => undefined