In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

haxe-like enum switch by throwing

http://haxe.org/ref/enums
Get Adobe Flash player
by wh0 08 Apr 2012
/**
 * Copyright wh0 ( http://wonderfl.net/user/wh0 )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/fIfd
 */

// forked from bkzen's throw で条件分岐
package  
{
    import flash.events.Event;
    import flash.events.MouseEvent;
    import com.actionscriptbible.Example;
    
    /**
     * throw 式条件分岐
     * @author jc at bkzen
     */
    public class Test90 extends Example 
    {
        private var cnt: uint;
        
        public function Test90() 
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }
        
        private function init(e: Event = null): void 
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            //
            trace("click");
            stage.addEventListener(MouseEvent.CLICK, onClick);
        }
        
        private function onClick(e:MouseEvent):void 
        {
            graphics.clear();
            var c:Color2 = foo();
            trace(c);
            graphics.beginFill(color2int(c));
            graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
            graphics.endFill();
        }
        
        private function color2int(c:Color2):uint {
            try { throw c; }
            catch (red:Red) { return 0xff0000; }
            catch (green:Green) { return 0x00ff00; }
            catch (blue:Blue) { return 0x0000ff; }
            catch (gray:Gray) { return 0x010101 * gray.v; }
            catch (rgb:RGB) { return rgb.r << 16 | rgb.g << 8 | rgb.b; }
            /* default */ return 0x000000;
        }

        
        private function foo():Color2 
        {
            switch (cnt++%5)
            {
                case 0: return new Red();
                case 1: return new Green();
                case 2: return new Blue();
                case 3: return new Gray(Math.random() * 128 + 128);
                case 4: return new RGB(Math.random() * 96, 255, Math.random() * 192);
            }
            // unreachable
            return null;
        }
        
    }

}

internal class Color2 { public function toString():String { return Object.prototype.toString.call(this) + ' ' + JSON.stringify(this); } }
internal class Red extends Color2 { }
internal class Green extends Color2 { }
internal class Blue extends Color2 { }
internal class Gray extends Color2 { public var v:int; public function Gray(v:int) { this.v = v; } }
internal class RGB extends Color2 { public var r:int, g:int, b:int; public function RGB(r:int, g:int, b:int) { this.r = r; this.g = g; this.b = b; } }