Skip to curriculum
Jump to the editor

6.4. Cycle through values on each call

Easy
Topics

This question is in

6. Functions and closures
5–10 min

A carousel shows slide 1, 2, 3 and then slide 1 again. A table row gets the next of three stripe colors. A load balancer sends each request to the next of four servers. Each is the same small tool: a function that hands out values in turn and wraps around at the end.

Write cycle(...values) in cycle.js. It returns a function. The first call of that function returns the first value, the next call the second, and after the last value it starts again from the first.

Signature

JAVASCRIPT
function cycle(...values) // returns a function
  • values: any number of values of any type.
  • The returned function takes no arguments (any it gets are ignored) and returns the next value. With no values, it returns undefined.

Requirements

  1. cycle returns a function.
  2. Calls return the values in order, starting with the first, and go back to the first after the last.
  3. With one value, every call returns it. With no values, every call returns undefined and nothing throws.
  4. Values are returned by position, so repeated values work: cycle("a", "a", "b") gives a, a, b, a, …
  5. Any value is returned as it is, including undefined, NaN, objects (the same object) and functions (not called).
  6. Each function made by cycle has its own position, and arguments passed to it are ignored.

Examples

JAVASCRIPT
const color = cycle("red", "green", "blue");
color(); // "red"
color(); // "green"
color(); // "blue"
color(); // "red"
JAVASCRIPT
const same = cycle("on");
same(); // "on"
same(); // "on"
JAVASCRIPT
const nothing = cycle();
nothing(); // undefined
JAVASCRIPT
const steps = cycle("a", "a", "b");
steps(); steps(); steps(); // "a", "a", "b"
steps();                   // "a"

Environment

  • Plain JavaScript in a browser page; the tests call the global cycle from cycle.js.
  • Out of scope: going backwards, jumping to a value and reading the current value without moving (problem 6.7 has those).

Hints

  1. What single number do you need to remember between calls?
  2. Which operator turns 3 back into 0 when there are 3 values?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…