Counter Function

Actionscript:
  1. var counter:Function = function(count:Array):Function{
  2.     var leng:int = count.length;
  3.     var index:int = 0;
  4.     return counter = function(reset:*=""):Function{
  5.         if (reset=="reset"){
  6.             index = 0;
  7.             return counter;
  8.         }else
  9.         if (reset is Array){
  10.             count = reset;
  11.             return counter;
  12.         }
  13.         trace(count[index % leng]);
  14.         index++;
  15.         return counter;
  16.     }
  17. }
  18.  
  19. // first time it's called you pass an array
  20. trace("count through the array:");
  21. // you can optionally call trigger the counter by calling the newly
  22. // returned function
  23. counter(["a","b","c"])();
  24. counter();
  25. counter();
  26. trace("change the array:");
  27. // here we choose to simply set the array and not trigger the counter
  28. counter([10,20,40,60,80]);
  29. counter();
  30. counter()
  31. trace("reset the counter:");
  32. // reset and the counter is called 3 times
  33. counter("reset")()()();
  34.  
  35. /*outputs :
  36. count through the array:
  37. a
  38. b
  39. c
  40. change the array:
  41. 10
  42. 20
  43. reset the counter:
  44. 10
  45. 20
  46. 40
  47. */

Today I felt like messing around with functions and this is the result. This snippet shows a strange and interesting technique to create a function that iterates through a given array in a few different ways.

I believe the technical term for this kind of thing is a continuation...

There are a bunch of other posts like this on actionsnippet. Some are purely experimental, others are actually quite useful... these can all be found in the functions category.

This entry was posted in dynamic, functions and tagged , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*