Search code examples
actionscript-3deque

Is there a deque in ActionScript 3


I would like a way to store upto three strings. When I get a new one, I want to add it to the bottom of the list and remove the one from the top of the list (the oldest one).

I know this can be done in python with a deque, but not sure how to implement it in AS3 or if it exsists already. The google search turned up some code on googlecode but it didn't compile.


Solution

  • You can store strings in an Array or Vector

    Array

    unshift() - Adds one or more elements to the beginning of an array and returns the new length of the array. The other elements in the array are moved from their original position, i, to i+1.

    pop() - Removes the last element from an array and returns the value of that element.

    var arr: Array = [ "three", "four", "five" ];
    
    arr.unshift( "two" ); 
    trace( arr );   // "two", "three", "four", "five"
    
    arr.unshift( "one" ); 
    trace( arr );    // "one , ""two", "three", "four", "five"
    
    arr.pop(); //Removes the last element 
    trace( arr );   // "one , ""two", "three", "four"
    

    So in your case:

    "I want to add it to the bottom of the list and remove the one from the top of the list (the oldest one)."

    var arr: Array = [ "my", "three", "strings" ];
    
    arr.unshift( "newString" ); //add it to the bottom of the list
    
    arr.pop(); // remove the one from the top of the list (the oldest one)
    

    You will have 3 strings in the array, and you can access them like this:

    trace( arr[0] );  //first element
    trace( arr[1] );  //second element
    trace( arr[2] );  //third element
    

    Vector

    Because you want to store only Strings, you could use Vector for better performance.

    Vector Class in short is a 'typed array' and has similar methods to Array.

    The only difference in your case would be in declaration:

    var vect: Vector.<String> = new <String>[ "my", "three", "strings" ];
    
    vect.unshift( "newString" );  //add it to the bottom of the list
    
    vect.pop(); // remove the one from the top of the list