forked from: Chapter 8 Example 6

by devtrain23 forked from Chapter 8 Example 6 (diff: 6)
♥0 | Line 54 | Modified 2010-08-13 06:10:22 | MIT License
play

ActionScript3 source code

/**
 * Copyright devtrain23 ( http://wonderfl.net/user/devtrain23 )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/eayZ
 */

// forked from actionscriptbible's Chapter 8 Example 6
package {
  import com.actionscriptbible.Example;
  public class ch8ex6 extends Example {
    protected var bookshelf:Array;
    
    public function ch8ex6() {
      bookshelf = new Array();
      bookshelf.push(new Book("Jonathan Strange & Mr Norrell",
        "Susanna Clarke", 2006));
      bookshelf.push(new Book("Anathem", "Neal Stephenson", 2008));
      bookshelf.push(new Book("VALIS", "Philip K. Dick", 1991));
      bookshelf.push(new Book("The Crystal World", "J.G. Ballard", 1966));
      
      trace("---- default sort");
      bookshelf.sort();
      traceBookshelf();
      
      var byDate:Function = function(a:Book, b:Book):Number {
        if (a.year == b.year) return 0;
        else if (a.year < b.year) return -1;
        else return 1;
      }
      
      trace("---- sorted by date with RETURNINDEXEDARRAY, leaving bookshelf unchanged");
      var indxArray:Array = bookshelf.sort(byDate, Array.RETURNINDEXEDARRAY);
      traceBookshelf();
      trace(indxArray);

      trace("---- sorted by date");
      bookshelf.sort(byDate);
      traceBookshelf();

      trace("---- by date numerically, descending");
      bookshelf.sort(byDate, Array.NUMERIC | Array.DESCENDING);
      traceBookshelf();     

      trace("---- by date using sortOn");
      bookshelf.sortOn(["year"], Array.NUMERIC);
      traceBookshelf();
      
      trace("---- by author using sortOn");
      bookshelf.sortOn(["author"], Array.CASEINSENSITIVE);
      traceBookshelf();
    }
    
    protected function traceBookshelf():void {
      trace(bookshelf.join("\n"));
    }
  }
  
}
class Book {
  public var title:String;
  public var author:String;
  public var year:int;

  public function Book (title:String, author:String, year:int) {
    this.title = title;
    this.author = author;
    this.year = year;
  }
  
  public function toString():String {
    return '"' + title + '", ' + author + ' (' + year + ')';
  }
}