Closure (PART 2)

In this exercise, we’re going to again practive closure by defining a toggle(..) utility that gives us a value toggler.

You will pass one or more values (as arguments) into toggle(..), and get back a function. That returned function will alternate/rotate between all the passed-in values in order, one at a time, as it’s called repeatedly.

  1. function toggle(/* .. */) {
  2. // ..
  3. }
  4. var hello = toggle("hello");
  5. var onOff = toggle("on","off");
  6. var speed = toggle("slow","medium","fast");
  7. hello(); // "hello"
  8. hello(); // "hello"
  9. onOff(); // "on"
  10. onOff(); // "off"
  11. onOff(); // "on"
  12. speed(); // "slow"
  13. speed(); // "medium"
  14. speed(); // "fast"
  15. speed(); // "slow"

The corner case of passing in no values to toggle(..) is not very important; such a toggler instance could just always return undefined.

Try the exercise for yourself, then check out the suggested solution at the end of this appendix.