Practicing Closure

Now let’s practice with closure (Chapter 4, Pillar 1).

The range(..) function takes a number as its first argument, representing the first number in a desired range of numbers. The second argument is also a number representing the end of the desired range (inclusive). If the second argument is omitted, then another function should be returned that expects that argument.

  1. function range(start,end) {
  2. // ..TODO..
  3. }
  4. range(3,3); // [3]
  5. range(3,8); // [3,4,5,6,7,8]
  6. range(3,0); // []
  7. var start3 = range(3);
  8. var start4 = range(4);
  9. start3(3); // [3]
  10. start3(8); // [3,4,5,6,7,8]
  11. start3(0); // []
  12. start4(6); // [4,5,6]

Try to solve this yourself first.

Once you have code that works, compare your solution(s) to the code in “Suggested Solutions” at the end of this appendix.