Hot File

How to Querying (and Conquering) Big Collections in AS3 With Realaxy Editor

View: 390    Dowload: 0   Comment: 0   Post by: hanhga  
Author: none   Category: Flash template, Flash game   Fields: Other

9 point/3 review File has been tested

Well, let's introduce the Collections AS3 language extension that is available in RASE Beta 10, build 8177+.

Introduction

Well, let's introduce the Collections AS3 language extension that is available in RASE Beta 10, build 8177+.

A complete vocabulary of methods supplemented with samples is available here: one for lists and another one for maps (these are images; scroll them down, they are really HUGE).

In order to not get lost in this jungle, let's take a look at some simple use cases. The first true-life sample demonstrates the conciseness of collection code:

We create a list, which can contain only int values.

  1. Then, we select only those that fulfil a condition (“where”).
  2. We do something with every picked element (“select”).
  3. We convert them to Strings (“select”).
  4. Finally, we cycle through the list and trace the result.

WhereselectselectMany - these operations are easy to use when you're building a query.

Operations like allanycontainsAll, and contains work perfectly in conditional phrases (“if” statements, etc).

To modify a list, we have a wide range of weapons: removeremoveAll,removeWhereremoveHeadremoveTail, etc.

For those persons who definitely have an eye for perversion we have prepared a bunch of operations like foldLeft/foldRightreduceLeft/reduceRight,intersect, etc.

Simply said, there are plenty of operations suited to every fancy and almost every task. In some operations you just transmit one or more values to it, in some other ones you add a closure.

The collection language is intentionally simple. It supports two types: List andMapMap is quite similar to a trivial Dictionary that holds some useful methods -keys, valuescontainsKeycontainsValue (useful for checks and conditions),pushMap (to merge values), removeKeyremoveValue, etc.

Maps are smart and fail-safe. They won't let you add an incorrect key or value:

Maps work well with any lists and queries.

There are also conversion operations that can be utilized to facilitate embedding the new Collections extensions to your actual pure-ActionScript project. Just take a trivial array (or vector) and apply the .toList operation. After processing a list (or a map) you can always convert it back to the old-school AS3 style using .toArray or.toVector.

To demonstrate how to get started with these collections, here's a step-by-step guide based on a trivial situation. Suppose your task is to create a "suggested users" list for a Twitter account. We have to process a very long collection of hundreds or thousands of objects, to retrieve a short list (that match a number of criteria) and to apply some operation on every item in that short list.

We'll not turn our attention to interacting with Twitter API, since our goal is only to show how to get started with the Collections language and to show advantages of a functional approach in working with collections in AS3.

Create a new project from scratch and name it Collections. If this is your first experience with the editor, we recommend you to read the Realaxy HelloWord Tutorial and/or Realaxy Overview For Beginners.

Now we need to create three classes to store the data structure:UserTwitterAccount and Message. We can do it from the Generate menu, which is available through right-clicking the code or pressing Ctrl+N.

Type the class name in a pop-up box.

Jump to the <> position and hit Enter.

Add the following fields: usernamesurname and id. The code will look like this:

Invoke the Ctrl+N menu again.

A new pop-up window will appear. Select all newly created fields and press OK.

Don't forget to add a text presentation to the User class. Add .toString() method — item 5 from the Ctrl-N menu (same as on screenshot to Step 2 and 6).

The User class is ready. Its code will look like this:

Using the same process as Steps 2-9 you have to create TwitterAccount and Message classes.

 

NB: To avoid a type error (like the one shown in the image above), you must import the Collections language from the Ctrl+L menu:

NB2: The TwitterAccount and Message classes should be cross-linked. In order for this to happen, after importing the Collections language, you have to create theMessage class, jump back to the TwitterAccount class and complete the line that caused an error.

NB3: Don't forget to add getters, setters and a .toString() method.

Now it's time to write some code in Main(). First, we need to add some fields. 

NB: Use the Smart Complete keyboard shortcut (Ctrl-Shift-Space) to save a little time while typing these phrases:

Since our tutorial is just a demo that shows a how to work with collections in AS3, we'll skip the part that refers how to get this data from Twitter API.

Let's just imagine that we already have:

  1. a list of our followers
  2. a list of users followedBefore,
  3. a very long list of potential candidates for following — candidatesLongList,
  4. and, of course, a candidatesShortList, which is empty at the moment.

The third collection can be extremly large, containing hundreds or even thousands of items. Our goal is to apply some sophisticated query and thus to cut off the needless items according to Buonarotti's principle “I saw the angel in the marble and carved until I set him free.”

Jump to Main() constructor, and enter the candidatesLongList with its method “where” (hit Ctrl-Space to use autocompletion like in the screenshot below):

The following phrase will appear:

Don't be surprised, it's just a Closure, and "it" is just its parameter.

A closure is, in fact, the same anonymous function, but with a number of small differences.

First, the Closure has a very concise syntax. Parameters don't have a type declaration (to be more precise, they have it, but such declarations are hidden). The Closure has a special behavior - “the last statement is a return value&rdquo - which means you should use “1;” (in the last line) instead of “return 1;

Second, it has a special view for single-line closures - in such a closure a semi-colon on the end is omitted (for two reasons: readability and brevity).

Unlike an anonymous function (and also as a counter to the aforementioned Arraysand Vectors), a closure is type safe. That means that autocomplete and type-checking will work in closures.

To conclude, a Closure is a kind of function on steroids. It has a lot of tasty features that helps us to write everything quick and concise.

Let's return to our unfinished closure. Add some code that will implement our "rules". This code will return a cut-down version of candidatesLongList that doesn't include any of our followers:

Then add another criterion:

Theoretically, the Collections language allows you to nest a lot of different conditions one by one. Let's add one more criterion (include users that have “Flash”, “ActionScript” or “Adobe” in their Biography field) using a regular expression:

Select the whole query and press Ctrl-Alt-V. A new variable will be introduced.

Now we are able to do whatever we want:

We would then copy the contents of result into candidatesShortList.

Build a module with Ctrl-F9 and take a look at the Output window. The generated pure AS3 code of Main() will look like this:

package com.example{
   
  import com.realaxy.actionScript.collections.util.CollectionsLanguageUtil;
  import flash.display.Sprite;
   
  public class Main extends Sprite {
 
    private var followers : Array = new Array() ;
    private var followedBefore : Array = new Array() ;
    private var candidatesLongList : Array = new Array() ;
    private var candidatesShortList : Array = new Array() ;
 
    public function Main(){
       
      //exclude our followers and users followed by us before
      //include people with "Flash", "ActionScript" and "Adobe" in their bio
      //add them all to the recommendations shortlist
 
      this.candidatesShortList = CollectionsLanguageUtil.where(CollectionsLanguageUtil.where(candidatesLongList,  
            
        function ( n : TwitterAccount, stops : Object ) : Boolean {
 
          return !CollectionsLanguageUtil.any(followers,      
              
            function ( f : TwitterAccount, stops : Object ) : Boolean {
              return f.user.id != n.user.id ;
            },
 
            this, false) && 
 
          !CollectionsLanguageUtil.any(followedBefore,     
               
            function ( f : TwitterAccount, stops : Object ) : Boolean {
              return f.user.id != n.user.id ;
            }, 
             
            this, false);            
        }, 
 
        this, false),   
             
          function ( it : TwitterAccount, stops : Object ) : Boolean {
            return /Flash|ActionScript|Adobe/.test(it.bio) ;
          }, 
 
        this, false);
       
      var names : Array = CollectionsLanguageUtil.select(candidatesShortList,       
 
        function ( it : TwitterAccount, stops : Object ) : String {
          return it.user.username + ", " + it.user.surname ;
        }, 
 
        this, false);
       
      CollectionsLanguageUtil.forEach(names,
 
        function ( m : String, stops : Object ) : void {
        //TODO: do something with 'm'
        }, 
 
        this, false);
    }
  }
}

Seems a little bit unreadable, eh? Especially comparing with our DSL code:

How to Querying (and Conquering) Big Collections in AS3 With Realaxy Editor

How to Querying (and Conquering) Big Collections in AS3 With Realaxy Editor Posted on 14-01-2016  Well, let's introduce the Collections AS3 language extension that is available in RASE Beta 10, build 8177+. 3/10 390

Comment:

To comment you must be logged in members.

Files with category

 
Newsletter Email

File suggestion for you

File top downloads

logo codetitle
Codetitle.com - library source code to share, download the file to the community
Copyright © 2015. All rights reserved. codetitle.com Develope by Vinagon .Ltd