kolnedra . com | 15 Useful AS3 code snippets

15 Useful AS3 code snippets

15 Useful AS3 code snippets

Date: 25 February 2010

A collection of self-made functions (aka snippets) to speed things up.

1. Check if an e-mail is valid
2. First character in uppercase
3. Random number
4. Shuffle an array
5. Does an element exist in an array
6. Remove an element from an array
7. The AS2 setRGB method
8. Reverse timeline animation
9. Get the file extension
10. Filesize
11. Hexadecimal to RGB object
12. Color to monochrome color
13. Crop a bitmap
14. Forces to run the garbage collection
15. Local to global position

1. Check if an e-mail is valid

/**
 * Checks if a string is a valid email (name@domain.com)
 * 
 * @usage	 var validEmail:Boolean = isValidMail("info@kolnedra.com");
 * @param	 $email The email to check
 * @return	Boolean
 */
		
function isValidMail($email:String):Boolean {
	var validEmailRegExp:RegExp = /([a-z0-9._-]+)@([a-z0-9.-]+)\.([a-z]{2,4})/i;
	return validEmailRegExp.test($email);
}

2. First character in uppercase

/**
 * First character is in uppercase
 * 
 * @usage		  var string:String = ucFirst("this is my blog"); 
 * @param $str	  String
 * @param $lcase	Boolean Lowercase the rest of the string (optional)
 * @return		  String
 */

function ucFirst($str:String, $lcase:Boolean = false):String {
	if ($lcase) { $str = $str.toLowerCase(); }
	return $str.substr(0, 1).toUpperCase() + $str.substr(1);
}

3. Random number

/**
 * Returns a random value
 * 
 * @usage	 var randomVal:int = random(0,100);
 * @param	 $int1	The from value, or when $int2 is not defined, this value is the to value
 * @param	 $int2	The to value
 * @return	Number
 */

function random($int1:Number=Number.MIN_VALUE, $int2:Number=Number.MAX_VALUE):Number  {
	var round:Boolean = false;
	if ($int1 == Number.MIN_VALUE) {
		$int1 = 1;
	} else {				
		round = true;
	}
	if ($int2 == Number.MAX_VALUE) {
		$int2 = $int1;
		$int1 = 0; 
	} else {
		round = true;
	}
	var val:Number = (Math.random() * ($int2 - $int1)) + $int1;
	if (round) {
		return Math.round(val);
	}
	return val;
}

4. Shuffle an array

/**
 * Randomizes an array
 * 
 * @usage 	var newArray:Array = Esites.arrayShuffle([1,2,3,4,5,6,7]);
 * @param	 $source The array to randomize
 * @return	Array
 */

function arrayShuffle($source:Array):Array {
	var $return:Array = [];
	while ($source.length > 0) {
		$return.push($source.splice(Math.round(Math.random() * ($source.length - 1)), 1)[0]);
	}
	return $return;
}

5. Does an element exist in an array

/**
 * Does an element exists in an array
 * 
 * @usage	var inA:Boolean = inArray([0,2,1,6,7,8], 1);
 * @param	$source	 Array
 * @param	$element	Element
 * @return   Boolean
 */

function inArray($source:Array, $element:*):Boolean {
	for (var i:int = 0; i < $source.length; i++) {
		if ($source[i] == $element) { return true; }
	}
	return false;
}

6. Remove an element from an array

/**
 * Remove an element from the designated array
 * 
 * @param	$source	 Array
 * @param	$element	Element
 * @return   Array
 */
function removeElementFromArray($source:Array, $element:*):Array {
	var newArray:Array = [];
	for (var i:int = 0; i < $source.length; i++) {
		if ($source[i] != $element) { newArray.push($source[i]);  }
	}
	return newArray;
}

7. The AS2 setRGB method

/**
 * The (old) AS2 setRGB function
 * 
 * @param	$displayObject 	The display object to change it's color
 * @param	$color 			The color
 */

function setRGB($displayObject:DisplayObject, $color:*):void {
	if ($color is Number) {
		$color = uint($color);
	} else if ($color is String) {
		if ($color.length < 8) {
			$color = "0x" + $color;
		}
		$color = uint(Number($color));
	}
	var newColorTransform:ColorTransform = $displayObject.transform.colorTransform;
	newColorTransform.color = $color;
	$displayObject.transform.colorTransform = newColorTransform;
}

8. Reverse timeline animation

/**
 * To reverse a timeline based animation
 * 
 * @usage	Esites.reversePlay(boatFlag, { framesPerStep: 2, callBackFunction: endAnimation, endFrame: 5, startPosition: 11});
 * @param	$target	The MovieClip to reverse play
 * @param	$params	Additional parameters
 */

function reversePlay($target:MovieClip, $params:Object=null):void {	if ($params == null) { $params = {}; }
	$target.stop();
	if ($params.startPosition) { $target.gotoAndStop($params.startPosition);	}
	if (!$params.endFrame) { $params.endFrame = 1; }
	if (!$params.framesPerStep) { $params.framesPerStep = 1; }
	
	$target.targetEnterFrame = function(e:Event):void {		
		if ($target.currentFrame <= $params.endFrame) { 
			$target.gotoAndStop($params.endFrame);
			$target.removeEventListener(Event.ENTER_FRAME, $target.targetEnterFrame);
			if ($params.callBackFunction != null) { $params.callBackFunction.call(null); }
			return;
		}
		$target.gotoAndStop($target.currentFrame - $params.framesPerStep);
	}	
	
	$target.addEventListener(Event.ENTER_FRAME, $target.targetEnterFrame);
}	

9. Get the file extension

/**
 * Returns the extension (in lowercase)
 * 
 * @param	$filename	The filename of a file
 * @return   String extension
 */

function getFileExtension($filename:String):String {
	return $filename.split(".")[($filename.split(".").length-1)].toLowerCase();
}

10. Filesize

/** Gives the filesize back including b, kb or mb
 * 
 * @param 	$bytes	int	The total number of bytes
 * @return	String
 */

function filesize($bytes:int):String {			
	var mb:int = 0;
	var b:int = $bytes;
	var kb:int = 0;
	while (b >= 1024*1024) {
		b -= 1024*1024;
		mb++;
	}
	while (b >= 1024) {
		b -= 1024;
		kb++;
	}
	var str:String;
	if (mb == 0) {
		str = kb+"kb";
	} else {
		str = mb + "." + (kb + "").substr(0,2)+"mb";
	}
	return str;
}

11. Hexadecimal to RGB object

/**
 * Hex value to RGB value
 *
 * @usage	 var rgbArray:Array = HEX2RGB(0xFF9900);
 * @param	 $hex	  Hexstring (0xFF9900)
 * @return	Object	{r: int, g: int, b: int}
 */
 
public static function HEX2RGB($hex:uint):Object {
	var r:int = $hex>>16;
	var gb:int = $hex - (r<<16);
	var g:int = gb>>8;
	var b:int = gb - (g << 8);
	return {r: r, g: g, b: b};
}

12. Color to monochrome color

/**
 * Translates a color to a greyscale color
 * Uses the HEX2RGB function
 *
 * @usage	var color:int = monoColor(0xFF9900);
 * @param	$color	uint (0-255)
 */

function monoColor($color:uint):int {
	var cArray:Array = HEX2RGB($color);
	return (0.2125 * cArray[0]) + (0.7154 * cArray[1]) + (0.0721 * cArray[2]);
}

13. Crop a bitmap

/**
 * Creates a crop of abitmap
 * 
 * @usage	 var croppedBitmap:Bitmap = new bitmapCrop(picture,10,10,500,400);
 * @param	 $displayObject	The movieclip/displayobject
 * @param	 $x	Left-top x-coordinate
 * @param	 $y	Left-top y-coordinate
 * @param	 $width	The width of the cropped area
 * @param	 $height	The height of the cropped area
 * @return	Bitmap
 */

function bitmapCrop($displayObject:DisplayObject, $x:Number, $y:Number, $width:Number, $height:Number):Bitmap {
	var cropArea:Rectangle = new Rectangle( 0, 0, $width, $height );
	var croppedBitmap:Bitmap = new Bitmap( new BitmapData( $width, $height ), PixelSnapping.ALWAYS, true );
	croppedBitmap.bitmapData.draw($displayObject, new Matrix(1, 0, 0, 1, -$x, -$y) , null, null, cropArea, true );
	return croppedBitmap;
}

14. Forces to run the garbage collection

/**
 * Cleans the garbage collection
 * 
 * @usage	cleanGC();
 */

function cleanGC():void {
	System.gc();
	try {
		new LocalConnection().connect('foo');
		new LocalConnection().connect('foo');
	} catch (e:*) {}			
}

15. Local to global position

/** Equivalant to the global prototype 'localToGlobal'
 * 
 * @usage	 var p:Point = local2Global(movieClip, root);
 * @param	 $obj		   MovieClip
 * @param	 $parent		The absolute parent
 * @return	Point		  x,y
 */

function local2Global($obj:MovieClip, $parent:MovieClip):Point {
	var point:Point = new Point($obj.x, $obj.y);
	var p:MovieClip = $obj.parent as MovieClip;
	var $go:Boolean = true;
	while ($go) {
		if (p == $parent) {
			$go = false;
		} else {
			point.x += p.x;
			point.y += p.y;
			p = p.parent as MovieClip;
		}
	}
	return point;			
}

Comments