Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT JAVASCRIPT
6.4. Cycle through values on each call
Easy
Topics
This question is in
6. Functions and closuresA 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
function cycle(...values) // returns a functionvalues: 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
cyclereturns a function.- Calls return the values in order, starting with the first, and go back to the first after the last.
- With one value, every call returns it. With no values, every call returns
undefinedand nothing throws. - Values are returned by position, so repeated values work:
cycle("a", "a", "b")givesa,a,b,a, … - Any value is returned as it is, including
undefined,NaN, objects (the same object) and functions (not called). - Each function made by
cyclehas its own position, and arguments passed to it are ignored.
Examples
const color = cycle("red", "green", "blue");
color(); // "red"
color(); // "green"
color(); // "blue"
color(); // "red"const same = cycle("on");
same(); // "on"
same(); // "on"const nothing = cycle();
nothing(); // undefinedconst 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
cyclefromcycle.js. - Out of scope: going backwards, jumping to a value and reading the current value without moving (problem 6.7 has those).
Hints
- What single number do you need to remember between calls?
- 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…