Usefull Array utils - SHUFFLE, Random, remove,


/ Published in: ActionScript 3
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. //The static methods only:
  2.  
  3. //SHUFFLE
  4. /*
  5. array - array to shufle
  6. startIndex = the start index of the element
  7. endIndex = int, should be array.length-1 to shuffle all
  8. */
  9. public static function shuffle(array:Array, startIndex:int = 0, endIndex:int = 0):Array{
  10. if(endIndex == 0){
  11. endIndex = array.length-1;
  12. }
  13. for (var i:int = endIndex; i>startIndex; i--) {
  14. var randomNumber:int = Math.floor(Math.random()*endIndex)+startIndex;
  15. var tmp:* = array[i];
  16. array[i] = array[randomNumber];
  17. array[randomNumber] = tmp
  18. }
  19. return array;
  20. }
  21.  
  22. //Random element
  23. static public function random(array:Array):*{
  24. return array.length ? array[Math.floor(Math.random()*array.length)] : null
  25. }
  26.  
  27. //removes elemnt from array
  28. public static function remove(array:Array, elem:*):Array {
  29. return array.filter(function(item:*, index:int, arr:Array):Boolean{ return item != elem })
  30. }
  31.  
  32. /**
  33. *Returns last element of the array
  34. **/
  35. public static function last(array:Array):*{
  36. return array.length ? array[array.length-1] : null;
  37. }
  38.  
  39. //previuos element of array
  40. static public function previous(array:Array, elem: *):*{
  41. return array.indexOf(elem) >=0 ? array[array.indexOf(elem)-1] : null;
  42. }
  43.  
  44. //next element of array (array, element)
  45. static public function next(array:Array, elem: *):*{
  46. return array.indexOf(elem) < array.length-1 ? array[array.indexOf(elem)+1] : null;
  47. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.