Overview
Implement cycle(...values) — returns a function that cycles through the values.
Examples
const next = cycle('a','b','c');
next(); // 'a'
next(); // 'b'
next(); // 'c'
next(); // 'a'Solution
Reveal solution
function cycle(...values) {
let i = 0;
return function() {
const v = values[i];
i = (i + 1) % values.length;
return v;
};
}cycle.js
Cycle
easycodingJavaScriptClosures
Overview
Implement cycle(...values) — returns a function that cycles through the values.
Examples
const next = cycle('a','b','c');
next(); // 'a'
next(); // 'b'
next(); // 'c'
next(); // 'a'Solution
Reveal solution
function cycle(...values) {
let i = 0;
return function() {
const v = values[i];
i = (i + 1) % values.length;
return v;
};
}NameTopicDifficulty
103 of 103 problems