A counter with private state
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Return a counter object with three methods. `next()` returns the current value and then moves the counter on by `step`. `peek()` returns the current value without changing it. `reset()` puts the counter back to `start`. So `makeCounter()` gives 0, 1, 2 on successive `next()` calls. `step` can be negative or 0. Every counter is independent of the others.
What this exercise teaches
The methods are closures: they keep access to the variables of the makeCounter call that created them, and nothing outside can reach those variables. Each call to makeCounter creates a fresh set of variables, which is why two counters do not disturb each other.
A hint if you get stuck
Keep the current value in a variable inside `makeCounter` and return an object whose methods read and change that variable. Use default parameters for `start` and `step` rather than `||`, which would replace a step of 0.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Async and functions
- Sleep with a PromiseFree
- Retry a failing callFree
- Promise.all with a concurrency limitFree
- DebounceFree
- MemoizeFree
- Run only onceFree
- Pipe functions togetherFree
- Timeout wrapperFree
- Run tasks in sequenceFree
- ThrottleFree
- Curry a functionFree
- Event emitterFree
- LRU cacheFree
- Write your own Promise.allFree
- Callback style to a PromiseFree