package { import flash.events.Event; import flash.events.EventDispatcher; import flash.display.Shape; /** * Performs a Caesar cipher on a string as an asynchronous * operation. */ public class CaesarCipher extends EventDispatcher { // ENTER_FRAME events dispatched by a composed DisplayObject // instance; one can be used for all CaesarCipher instances private static var enterFrameDispatcher:Shape = new Shape(); // determines how many loop iterations are run before // waiting for the next ENTER_FRAME event private static const MAX_ITERATIONS:int = 3; /** * Final Caesar cipher value after run() completes and * an Event.COMPLETE event is dispatched. */ public var result:String; private var text:String; // retained text to be processed private var shift:int; // retained argument used in processing private var resultString:String; // temporary result while processing private var savedIndex:int; // start index for each loop /** * Constructor for new CaesarCipher instances. * @param text Text to apply a Caesar cipher to. * @param shift The number of characters to shift. */ public function CaesarCipher(text:String, shift:int = 3) { this.text = text; this.shift = shift; } /** * Starts the ciphering process. An Event.COMPLETE event * will fire when its complete. The result is accessible * from the result property. */ public function run():void { // initialize values resultString = ""; savedIndex = 0; // set up ENTER_FRAME loop enterFrameDispatcher.addEventListener(Event.ENTER_FRAME, loopHandler, false, 0, true); // call the first iteration immediately loopHandler(null); } // ENTER_FRAME loop for asynchronous processing private function loopHandler(event:Event):void { // loop through each character in the saved // text to cipher it into resultString var i:int; var n:int = text.length; // resume from last saved index for (i=savedIndex; i= MAX_ITERATIONS){ savedIndex = i; return; } // process loop iteration: var code:int = text.charCodeAt(i); // shift capital letters if (code >= 65 && code <= 90){ code = 65 + (code - 65 + shift) % 26; } // shift lowercase letters if (code >= 97 && code <= 122){ code = 97 + (code - 97 + shift) % 26; } // update temporary string with new // shifted character code resultString += String.fromCharCode(code); } // loop has completed without exiting // process is complete // copy result into user-accessible variable result = resultString; // cleanup temporary data resultString = null; // remove ENTER_FRAME event handler enterFrameDispatcher.removeEventListener(Event.ENTER_FRAME, loopHandler, false); // signal to listeners that processing is complete // and the results value is available dispatchEvent(new Event(Event.COMPLETE)); } } }