Function Chaining & Classes

Actionscript:
  1. package {
  2.     import flash.display.Sprite;
  3.     public class Chaining extends Sprite{
  4.         public function Chaining(){
  5.               print(n(100).divide(2).plus(2));
  6.               // outputs 52              
  7.               print(n(100).plus(n(10).multiply(2)));
  8.               // outputs 120
  9.         }
  10.     }
  11. }
  12.  
  13. function print(n:Num):void{
  14.    trace(n.getValue());
  15. }
  16. function n(n:Number):Num{
  17.    return new Num(n);
  18. }
  19.  
  20. class Num{
  21.     private var value:Number;
  22.    
  23.     public function Num(n:Number):void{
  24.        value = n;
  25.     }
  26.     private function convert(n:*):Number{
  27.         if (n is Num) n = n.getValue();
  28.         return n;
  29.     }
  30.     public function getValue():Number{
  31.         return value;
  32.     }
  33.     public function plus(n:*):Num{
  34.         n = convert(n);
  35.         value += n;
  36.         return this;
  37.     }
  38.     public function minus(n:*):Num{
  39.         n = convert(n);
  40.         value -= n;
  41.         return this;
  42.     }
  43.     public function multiply(n:*):Num{
  44.         n = convert(n);
  45.         value *= n;
  46.         return this;
  47.     }
  48.     public function divide(n:*):Num{
  49.         n = convert(n);
  50.         value /= n;
  51.         return this;
  52.     }
  53. }

This snippet is meant to be run as a document class. It shows how one might go about designing a class to make extensive use of function chaining.

This entry was posted in OOP, functions and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. brendan
    Posted April 2, 2009 at 9:00 am | Permalink

    Check this out -
    http://drawlogic.com/2008/04/24/as3query-actionscript-port-of-jquery/

  2. Posted April 2, 2009 at 9:59 am | Permalink

    thanks for the link brendan. I’ve seen this before, very cool stuff… that same guy has a bunch of other interesting projects… some of which are here.

Post a Comment

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

*
*