Posted By

burnandbass on 12/03/10


Tagged

random array remove shuffle utils


Versions (?)

Who likes this?

7 people have marked this snippet as a favorite

alptugan
onemanstudio
mitien
albertomori
tuffstudio
flashdeveloper
letmein_xxi


Usefull Array utils - SHUFFLE, Random, remove,


 / Published in: ActionScript 3
 

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

  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  

You need to login to post a comment.