Return to Snippet

Revision: 37099
at December 3, 2010 22:59 by burnandbass


Initial Code
//The static methods only:

//SHUFFLE 
/*
array - array to shufle
startIndex = the start index of the element
endIndex = int, should be array.length-1 to shuffle all
*/
public static function shuffle(array:Array, startIndex:int = 0, endIndex:int = 0):Array{ 
			if(endIndex == 0){
				endIndex = array.length-1;
			}
			for (var i:int = endIndex; i>startIndex; i--) {
				var randomNumber:int = Math.floor(Math.random()*endIndex)+startIndex;
				var tmp:* = array[i];
				array[i] = array[randomNumber];
				array[randomNumber] = tmp
			}
			return array;
		}

//Random element
	static public function random(array:Array):*{
			return array.length ? array[Math.floor(Math.random()*array.length)] : null
		}

//removes elemnt from array
	public static function remove(array:Array, elem:*):Array {
			return array.filter(function(item:*, index:int, arr:Array):Boolean{ return item != elem })
		}
		
		/**
		*Returns last element of the array
		**/
		public static function last(array:Array):*{
			return array.length ? array[array.length-1] : null;
		}
		
//previuos element of array
		static public function previous(array:Array, elem: *):*{
			return array.indexOf(elem) >=0 ? array[array.indexOf(elem)-1] : null;
		}
		
//next element of array (array, element)
		static public function next(array:Array, elem: *):*{
			return array.indexOf(elem) < array.length-1 ? array[array.indexOf(elem)+1] : null;
		}

Initial URL

                                

Initial Description
Sometimes you need special array functions, not build in AS3. Special ArrayUtils class with some static methods can help us :)

Initial Title
Usefull Array utils - SHUFFLE, Random, remove,

Initial Tags
array

Initial Language
ActionScript 3