Vous êtes sur la page 1sur 47

1

Action Script Functions


Compiler Date Type Version Aditya Kappagantula 21-1-12 Actionscript Functions Actionscript 3

Note: Refer the index page [2] for function descriptions. Note: Please add any other functions that you find useful. Also please add the function name in index page. Note: Search for the function name to navigate to the function.

INDEX 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

NAME Basic Array Shuffler 2d Array from text file 7 out of 49 lottery count (a1+a2+---an)*(b1+b2+---bm) Add values in arrays Array Unique Array flip Array.addItemAt(item, index) Array.removeItemAt(index) Array.bSearch (key, options) - search a sorted associative array using bisection algorithm Array.contains() Array.Contains_Mod() Array.distinctShuffle() Array.fromFile() Array.inArray() Array.moveElement(index,num) Array.moveItem Array.next(); Array.previous() Array.prototype.arrayToVar Array.qsort Array.unique() arrayMul Average from nested arrays Bubble sort Compare Arrays Copies an array rather than just creating a reference to an array copyArray Find and remove Find nearest value Find the index of a string in array For-in loop Get max and min values in an array Join two arrays element by element Array shuffler random number generation recording keystrokes into an array Remove repeated items Xml to array [recursive] Popup manager Transition Class Count Down timer Birthdate to Age Date Date extension class Digital clock

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

set number to 2 decimal places


Round to nearest format number with commas Format numbers with commas efficiently Random alpha numeric password generator roman to Arabic Drag and drop class Trace Object Class Bad word filter Word counting is Prime Tooltip class Array Collection filter function Center of Stage

Array Collection to XML Unique Array Collection Values Convert XML TO ArrayCollection

96 97 Basic Array Shuffler


function sortRand () { if (random(2) == 0) { return -1; } if (random(2) == 0) { return 1; } }

array.sort(sortRand);

2D Array from text file


*this works for the MySecondaryArray having only exactly 3 fields. i'm sure it could be done so that it adjusts automatically but i didnt need it to so i didnt bother. the text file goes like this : myTextFileVar=this;;that::the next;;\n\nthis2;;that2: :the next2;;\n\nthis3;;3that::3the next& where each "\n" is a carrige return in the text file meaning there is 1 line between listed items to make it easier to use, and "&" is the absolute last character to indicate the end of the variable. if lost use trace actions to figure out what does what. enjoy.*/ _root.myConstuctor = new LoadVars(); _root.myConstuctor.load("MytextFile.txt"); _root.myConstuctor.onLoad = function(true) { if (true) { _root.myParsingVar1 = _root.myConstuctor.myTextFileVar; _root.myParsingArray = _root.myParsingVar1.split("\n\n"); _root.myMainArray = new Array(); for (j=0; j<_root.myParsingArray.length; j++) { for (n=0; n<3; n++) { _root.myParsingVar2 = _root.myParsingArray[j]; _root.mySecondaryArray = _root.myParsingVar2.split(";;"); } _root.myMainArray[j] = _root.mySecondaryArray; } } };

7 out of 49 Lottery
/*how to do a lottery? Draw 7 (unique) out off 49 balls for example */ pickfrom = new Array(); winlist = new Array(); all = 9;//49 easy to configure shown = 7;//show 7 winner for (i=0; i<all; i++) { pickfrom[i] = i+1; } trace("2003 by www.advance-media.com \nBegin: "+pickfrom); for (i=0; i<shown; i++) { rand = Math.floor(Math.random()*(all-i)); winlist[i] = pickfrom[rand];

5
pickfrom.splice(rand, 1); } trace("Rest: "+pickfrom+"\nShow Winner: "+winlist); /* I used it for loading 7 randomly picked movies (holding nothing but pictures) out of 17 total and no repetition! Each time the user clicks back to the site he gets to see different pix on my slider bar....*/

a count
//count (a1+a2+---an)*(b1+b2+---bm) //author: tigerchina k=0 Number.prototype.mu=function(a,b){ for(i=0;i<a.length;i++){ for(j=0;j<b.length;j++){ this=this+a[i] *b[j] } }return this } temp=new Number() a=new Array(1,6) b=new Array(3,4,7) trace(temp.mu(a,b))

Add values in arrays


[10,10] + [5,-5] = [15, 5]
This function ads only. I thought of making it a prototype but then I thought better of it, as it's prolly more useful as a function for iterative applications, etc. Enough talk, here it is:

// Add values in arrays V1 // Jesse Stratford, www.actionscript.org function arrayAdd (a, b) { tmp = new Array(); // Math.max used to ensure no items are dropped // if one array is longer than the other for (var j = 0; j<Math.max(a.length, b.length); j++) { tmp[j] = a[j]+b[j]; } return tmp; } // Usage Examples answer = arrayAdd([10, 10], [5, -5]); answer2 = arrayAdd([10, 10], [5, -5, 10]); // Note answer2.length = 3

Array Unique
// This script was already posted, but with an error, so i corrected it // The other script didnt split tree or more equal elements side by side // like this: a = [1,1,1,1] returned a = [1,1] // // // // This script splits the equal elements from an array Usage: a = [1,1,1,1,1,1]; a = a.unique(); now a = [1];

Array.prototype.unique = function() { for (i=0; i<this.length; i++) { for (j=0; j<this.length-i; j++) { if (this[i] == this[i+j+1]) { this.splice(i+j+1, 1); j--; } } } return this; }; // Now its correct =]

Array flip
function flip (arr) { var tmp = new Array(); L = arr.length; for (i=0; i<arr.length; i++) { tmp.push(arr[L-1]); L = L-1; } return tmp; } temp = new Array(5, 10, 15, 20, 25, 30, 35, 40); temp = flip(temp); trace (temp);

Array string search


arr = ["Apollo", "Bacchus", "Ianus", "Iupiter", "Mars", "Mercurius"]; Array.prototype.sucher = function(w) { trace(this); var resD = []; var resC = []; for (i in this) { if ((this[i].indexOf(w, 0) != -1)) { resD.push(this[i]); resC.push(i); } } if (resD.length == 0) { return (-1); } else { resC.shift(); resC = resC.reverse(); return (resC); } }; trace(arr.sucher("us"));

Array.addItemAt(item, index)
Array.prototype.addItemAt = function( item , index ){ return( [ this.slice( 0 , index ) , item , this.slice( index , this.length ) ] ); } var neto = [ 10 , 20 , 40 , 50 , 60 ];

trace( neto.addItemAt( 30 , 2 ) );

Array.removeItemAt(index)
// // // // // // // This is a modification of Joo Neto's code to do the opposite of his function 'addItemAt'. This function removes an item from the array at the location specified. Be careful as the index for this function starts from 1 not 0 i.e. if removeItemAt(1) is called the first element is removed, not the second.

Array.prototype.removeItemAt = function(index){ if(index <= 1) return this.slice(index , this.length ); else { var firstHalf:Array = this.slice( 0 , index ); firstHalf.pop(); var secondHalf:Array = this.slice( index , this.length ); return [firstHalf,secondHalf]; } } //////// EXAMPLE var myArray:Array = Array("1","2","3","4","5","6","7","8","9","10"); trace(myArray); // 1,2,3,4,5,6,7,8,9,10 trace("**************"); trace(myArray.removeItemAt(4)); // 1,2,3,5,6,7,8,9,10

Array.bSearch (key, options) - search a sorted associative array using bisection algorithm
// Array.bSearch(key, options) // // Usage // my_array.bSearch( {role1: value1, role2: value2, ... , roleN: valueN} ) // my_array.bSearch( {role1: value1, role2: value2, ... , roleN: valueN}, Array.DESCENDING | Array.NUMERIC | Array.CASEINSENSITIVE ) // // Parameters // key A list of field names (roles) and their associated values of any data type to search, grouped together into a block using curly braces {}. // options Optional parameters that change the search behavior. Supported options are: Array.DESCENDING, Array.NUMERIC, Array.CASEINSENSITIVE. // // Returns // Integer value representing an array row (index) in which the search key was found, or -1 when not found. // A warning is displayed in output window via a trace(), when search takes more than theoretical maximum of log2(n) iterations. // // Description // Extension to class Array() to search for a key in a sorted associative array using very efficient bisection algorithm. // Array to search can use any data type since search key and array rows are converted to strings. // Array must be sorted prior to using this search method. // // References: // ActionScript Array.sortOn() for details on associative array sorting and sorting options. // Numerical Recipes section 3.4: bisection search algorithm, www.nr.com. // // Author: Ron Fredericks, Embedded Components, Inc., ronf@EmbeddedComponents.com // Last updated: Dec. 28, 2004 // Tested environment: Flash player version 6, and 7 (both as1 and as2).

8
// Copyright: no rights reserved, no liability covered, no warranty of use given or implied, no indemnity offered, support optional. Array.prototype.bSearch = function (key, options) { this.sortDESCENDING = (options & Array.DESCENDING) ? true : false; this.sortNUMERIC = (options & Array.NUMERIC) ? true : false; this.sortCASEINSENSITIVE = (options & Array.CASEINSENSITIVE) ? true : false; this.padRole = String.fromCharCode(31); // Use this character to delimit fields in search key and array test row. var iL = 0, iU = this.length-1, iM = 0; // Initialize search boundry. var iterations = 0; // The bisection search algorithm iterates about log2(Array.length) times when searching a sorted array. while (iU-iL > 1) { iM = (iU+iL) >> 1; // Bisect array's search boundary until search key is found in the array row under test, or search fails boundary conditions. iterations++; this.getRow2Test(key, iM); // Private function, defined below, to populate this.sKey and this.tKey. if ( (this.sKey >= this.tKey) != this.sortDESCENDING) iL=iM; else iU=iM; } if ( iterations > Math.round(Math.LOG2E*Math.log(this.length)) ) { trace( "Warning: search took too long! \n Details: " + iterations + " iterations of outer search loop were used, \n compared to theoretical maximum of log2(array size): " + Math.round(Math.LOG2E*Math.log(this.length)) ); trace( " Perhaps this array has not been sorted correctly, or different options should be pased to this function." ); } this.getRow2Test(key, (this.sortDESCENDING ? iU: iL)) // Return with Array index position when search found. if ( this.sKey == this.tKey ) return (this.sortDESCENDING ? iU: iL); this.getRow2Test(key, 0) if (this.sKey == this.tKey) return 0; this.getRow2Test(key, this.length-1) if (this.sKey == this.tKey) return this.length-1; return -1; // Return -1, when search key not found. }; // bSearch private function builds formatted search key (this.sKey) and test row (this.tKey) Array.prototype.getRow2Test = function (key, row) { this.sKey=""; // Search key. this.tKey=""; // Test row. for (var role in key) { var iPadRole = Math.max( String(key[role]).length, String(this[row][role]).length ) + 1; if ( typeof key[role] == "number" && this.sortNUMERIC) { // NUMERIC sorted number elements must pad to the right for (var p = String(key[role]).length; p<iPadRole; p++) this.sKey += this.padRole; for (var p = String(this[row][role]).length; p<iPadRole; p++) this.tKey += this.padRole; this.sKey += String(key[role]) this.tKey += String(this[row][role]) } else { // STRING sorted elements must pad to the left this.sKey += String(key[role]) this.tKey += String(this[row][role]) for (var p = String(key[role]).length; p<iPadRole; p++) this.sKey += this.padRole; for (var p = String(this[row][role]).length; p<iPadRole; p++) this.tKey += this.padRole; } } if (this.sortCASEINSENSITIVE) {

9
this.sKey = this.sKey.toUpperCase(); this.tKey = this.tKey.toUpperCase(); } }; // example... var playList = new Array(); playList.push( {slide: 2, clip: "_level0.instance3", cue: 4000} ); playList.push( {slide: 3, clip: "_level0.instance1", cue: 5000} ); playList.push( {slide: 1, clip: "_level0.instance1", cue: 1000} ); playList.push( {slide: 10, clip: "_level0.instance2", cue: 2000} ); playList.sortOn( ["clip", "slide"], Array.DESCENDING | Array.NUMERIC | Array.CASEINSENSITIVE) var index = playList.bSearch( {clip: "_level0.instance1", slide: 1}, Array.DESCENDING | Array.NUMERIC | Array.CASEINSENSITIVE ) if (index) trace("clip found, with cue time: " + playList[index].cue); // clip found, with cue time: 1000 else trace("Oops, clip not found");

Array.contains()
/*-------------------------------------------------------------------Array.Contains(value) A function to find if value is contained inside the array anywhere... Author: David B. (david@jmbsoftware.net) Date: July 13, 2003 Version: 0.1a License: As is! You assume all responsibility for this code. Use as you see fit. Use at your own risk! Inputs: [value] = the value to find inside the array. Returns: [int] = the number of occurrence of that [value] inside the array. Example: var a; var cnt; a = new Array(1,2,3,3,3,4); cnt = a.Contains(3); trace(cnt); ------------------------------------------------------------------------*/ Array.prototype.Contains = function(value) { var found = 0; var i = 0; for(i=0; i<this.length; i++) if( this[i] == value ) found++; return found; }

Array.Contains_Mod()
// many thanks to Array.Contains... // here's a little modification //returning the string where the searched was found and case sensitive

10
Array.prototype.Contains = function (value) { loc = new Array (); var found = 0; var i = 0; for (i = 0; i < this.length; i++) { if (this[i] == value or (this[i].indexOf (value) <> -1)) { loc.push (this[i]); found++; } } return found + ' [' + value + '\'s] found' + ' => ' + loc.toString (); delete loc; }; choice = new Array (); choice[0] = new Array ('ffo', 'mAry', 'envelope', 'mary', 'choA', 'a', 'Abraoa'); choice[1] = new Array (5, 43, 24, 33, 5563, 3346, 34, 3, 345, 3, 243); choice[2] = new Array (354, 3, 678, 112, 74564, 1, 423, 26, 4678, 1245678, 44); trace (choice[1].Contains ('5')); trace (choice[0].Contains ('a')); trace (choice[0].Contains ('A')); trace (choice[0].Contains ('oA'));

Array.distinctShuffle()
//Simple array randomiser... Array.prototype.distinctShuffle = function() { this.sort(function(a,b) { i = Math.round((Math.random() * 100) 50); return i;}); return this; }; var n = new Array(1,2,3,4,5,6,7,8,9,10); trace(n); n.distinctShuffle(); trace(n); n.distinctShuffle(); trace(n); n.distinctShuffle(); trace(n); stop();

Array.distinctShuffle()
/* I needed a script that would randomise an array and return a completely unique array. Each element had to have a new position. I came across a script entitled "Randomize an array with no similarities to previous layout" at: http://www.actionscript.org/actionscripts_library/Array_Object/ but after testing it found that an error occurs when unshift() is used. The resulting array is only completely unique in cases where unshift() isn't applied. Here is my solution, tested and working in Flash 5 and above:

11
*/ /*-------------------------------------------------------------------*/ Array.prototype.distinctShuffle = function() { result = []; for (posArray=[], i=0; i<this.length; posArray[i]=i++); for (last=this.length-1; last>=0; last--){ selected = this[last]; rand = random(posArray.length-1); lastPos = posArray.getPos(last); if (lastPos == null){ result[posArray[rand]] = selected; posArray.splice(rand, 1); }else{ posArray.splice(lastPos, 1); result[posArray[rand]] = selected; posArray.splice(rand, 1); posArray.push(last); } } return result; }; Array.prototype.getPos = function(item){ for(i=0; i<this.length; ++i) { if (this[i] == item) { return i; } } return null; }; /*-------------------------------------------------------------------*/ // Usage Array.prototype.checkError = function(nArray) { for (i=0; i<this.length; i++) { if (this[i] == nArray[i]) { return "found"; } } return "none" }; a = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]; b = a.distinctShuffle(); trace("original array : " + a); trace("shuffled array : " + b); trace("error: " + a.checkError(b)); trace("------------------------------------"); /*-------------------------------------------------------------------*/

Array.fromFile()
//File data format the same as for LoadVars :) Array.prototype.fromFile = function(file) { this.__proto__.__proto__=LoadVars.prototype this.load(file); }; myArray=[] myArray.fromFile("data.txt") // enjoy!

12

Array.inArray()
Array.prototype.inArray = function (value) // Creates a new method for the array object. // Returns true if the passed value is found in the // array -- by matching for identity, not similarity. // Returns false if the item is not found. { var i; for (i=0; i < this.length; i++) { // Matches identical (===), not just similar (==). if (this[i] === value) { return true; } } return false; };

Array.moveElement(index,num)
//Array.moveElement(index,num) // index - element in array to move // num - move Array elements up(postive num, towards index 0) or down(negative num, towards end of array) Array.prototype.moveElement = function(index,num){ var num=int(num); if(num>0){ //move upward num times var i=index; while(i>index-num){ if(i==0) break; var e = this[i];//this.slice(i,i+1); this.splice(i,1); this.splice(i-1,0,e/*.slice()*/; i--; } }else if(num<0){ //move downward num times var i=index; while(i<index-num){ if(i==this.length-1) break; var e = this[i];//this.slice(i,i+1); this.splice(i,1); this.splice(i+1,0,e/*.slice()*/; i++; } } } ASSetPropFlags(Array.prototype,"moveElement",1); //hide from for... in //example myArray = ["hello","goodebye",["one","two","three"],"stay awhile"]; trace(myArray); myArray.moveElement(1,-5); trace(myArray);

Array.moveItem
myArray = new Array("A", "B", "C", "D"); Array.prototype.moveItem = function(item) { var tmp = new Array(); for (j=0; j<this.length; j++) { if (this[j] !=item) { tmp.push(this[j]); } } tmp.push(item); display(tmp); };

13
myArray.moveItem("C"); function display(c) { trace(c.toString()); }

Array.next(); Array.previous()
Array.prototype.next=function (currentValue){ var setKey; for (at in this) { if (currentValue == this[at]){ return this[setKey]; } setKey=at; } } Array.prototype.prev=function (currentValue){ var setKey; var i=0; for (at in this) { if (setKey==i){ return this[at]; } if (currentValue == this[at]){ setKey=(i+1); } i++; } } ASSetPropFlags(Array.prototype,["next","prev"],1); /* example

flashzone=new Array(); flashzone[1]="1-1-1"; flashzone[3]="3-3-3"; flashzone['kk']="kkvalue"; flashzone[7]="7-7-7"; flashzone[25]="25-25-25"; flashzone['zz']="zzValue"; flashzone[11]="11-11-11"; flashzone[13]="13-13-13"; trace("nextValue=> " add flashzone.next("kkvalue")) trace("================") trace("prevValue=> " add flashzone.prev("11-11-11")) */

Array.prototype.arrayToVar
// Arrayelemnts to Variables Array.prototype.arrayToVar = function(varname) { if (varname == undefined) varname = "variable"; for (var i = 0; i < personen.length; i++) { _root[varname+"_"+i] = personen[i]; } }; ASSetPropFlags(Array.prototype,"arrayToVar",1,true); personen = ["Matthias","Caroline","Martin","Ralf"]; personen.arrayToVar("person"); // Try for (i in _root) { // trace(i + "=" + _root[i]); ausgabe_txt.text += i+"="+_root[i]+"\n";

14
}

Array.qsort
Array.prototype.qsort = function( obj ){ var type = []; if ( ( typeof obj == "object" ) && ( obj.length == undefined ) ) type.push( obj ); else type = obj; this.qs( 0 , this.length - 1 , type[ 0 ].prop ); if ( type[ 0 ].order == -1 ) this.reverse(); if ( type.length > 1 ){ for ( var i = 1 var ret var aux while ( i - 1 ].prop ] ){ ret.push( aux ); aux = []; } } for ( var j = 0 ; j < ret.length ; j++ ){ var a = ret[ j ] if ( a.length > 1 ) a.qs( 0 , a.length - 1 , type[ i ].prop ); if ( type[ i ].order == -1 ) a.reverse(); for ( var k = 0 ; k < a.length ; k++ ){ this.push( a[ k ] ); } } } } } Array.prototype.qs = function( left , right , prop ){ var nInt = function( value ){ return( int( value ) == value ? value : int( value ) } var i = left; var j = right; var x = this[ nInt( ( i + j ) / 2 ) ]; do { if ( prop == undefined ){ while ( ( this[ i ] < x ) && ( i < right ) ) while ( ( this[ j ] > x ) && ( j > left ) ) } else { while ( ( this[ i ][ prop ] < x[ prop ] ) && i++; while ( ( this[ j ][ prop ] > x[ prop ] ) && ; } if ( i <= j ){ var aux = this[ i ]; this[ i ] = this[ j ]; this[ j ] = aux; i++; j--; } } while( i <= j ); if ( left < j ) this.qs( left , j , prop ); if ( right > i ) this.qs( i , right , prop ); } ASSetPropFlags( Array.prototype , [ "qs" , "qsort" ] , 7 , true ); ; i < type.length ; i++ ){ = []; = []; this.length > 0 ){ aux.push( this.shift() ); if ( this[ 0 ][ type[ i - 1 ].prop ] != aux[ 0 ][ type[

+ 1 );

i++; j--; ( i < right ) ) ( j > left ) ) j--

15
var num = [ 10 , 16 , 33 , 1 , 15 , 21 ]; var str = [ "Joao" , "Jonas" , "Navy" , "Joao" , "Joao" , "Neto" ]; var obj = [ { nome : "Joao" , idade : 10 , local : "ap" }, { nome : "Jonas" , idade : 16 , local : "rj" }, { nome : "Navy" , idade : 33 , local : "sc" }, { nome : "Joao" , idade : 1 , local : "cp" }, { nome : "Joao" , idade : 15 , local : "bp" }, { nome : "Neto" , idade : 21 , local : "rs" } ]; num.qsort(); str.qsort(); obj.qsort( [ { prop : "nome" , order : 1 } , { prop : "idade" , order : -1 } ] ); trace( num ); trace( str ); for ( var i = 0 ; i < obj.length ; i++ ){ var p = ""; for ( var j in obj[ i ] ) p += j + ": " + obj[ i ][ j ] + " , "; trace( p ); }

Array.randomize()
Array.prototype.randomize = function () { return this.sort(function(a,b) {return (Math.floor(Math.random()*2) == 0) ? 1 : -1;}); }; myArray = [1,2,3,4,5,6,7,8,9,10]; trace(myArray.randomize());

Array.unique()
Array.prototype.unique = function() { for (i=0; i<this.length; i++) { for (j=0; j<this.length-i; j++) { if (this[i] == this[i+j+1]) { this.splice(i+j+1, 1); j--; } } } return this; };

arrayMul
This is just a modified version of ArrayAdd, so that you can multiply two arrays together ... // Mul values in arrays V1 function arrayMul (a, b) { tmp = new Array(); // Math.max used to ensure no items are dropped // if one array is longer than the other for (var j = 0; j<Math.max(a.length, b.length); j++) { tmp[j] = a[j]*b[j]; } return tmp; } // Usage Examples answer = arrayMul ([10, 10], [5, -5]);

16
answer2 = arrayMul ([10, 10], [5, -5, 10]); // Note answer2.length = 3

Average from nested arrays


//function by missing-link //first we create our function Array.prototype.getNestedAverages = function(){ //create a new array to hold the averages averages = new Array(); //now for the loop statements for (var i = 0; i<this[0].length; i++){ for (var j = 0; j<this.length; j++){ //store the average of each nested element in the new array averages[i]+=(this[j][i])/this.length; } } //trace it to see the results trace(averages); } //now create the arrays to store in the main array bowler1 = new Array(120, 135, 138); bowler2 = new Array(140, 160, 157); bowler3 = new Array (180, 189, 196); bowler4 = new Array (70, 65, 101); //now create the array to hold the other arrays team1 = new Array (bowler1, bowler2, bowler3, bowler4); //now invoke the function team1.getNestedAverages(); //output: 127.5,137.25,148

Bubble sort
//numerical sorting tester=[54,6,1,346,32,55,3,66,28] trace("original array :"+tester); tester1=new Array(); array.prototype.bubble=function(){ arr_t=new Array(); count=this.length; trace("arrray's length:"+count); temp=0; for(i=count-1;i>0;i--){ for(j=0;j<i;j++){ if(this[j]>this[j+1]){ temp=this[j]; this[j]=this[j+1]; this[j+1]=temp; } } } return this; } tester1=tester.bubble(); trace("bubbleed array:"+tester);

Compare Arrays

17
This script compares arrays and counts the number of items which are in both arrays but in the wrong place, and in both arrays in the same (right) place. I can forsee problems if the arrays sometimes have duplicate numbers like array1=[6,2,2,7] but other than that this should work:

array1=[5,3,6,1]; array2=[1,5,4,6]; for (var j = 0; j<array1.length; j++) { for (var k = 0; k<array2.length; k++) { if (array1[j] == array2[k]) { if (j != k) { rightNumWrongPlace++; } else { rightNumRightPlace++; } } } }
obviously if rightNumRightPlace == array1.length; then the arrays are identicle. Copies an array rather than just creating a reference to an array

//tester=[1,2,3,4] //tester2=tester.copy() Array.prototype.copy=function(){ return this.slice() }

copyArray
Array.prototype.copyArray = function(){ var tmp_arr = [] for(var i = 0; i < this.length; i++){ if(this[i] instanceof Array) tmp_arr.push( this[i].copyArray() ) else tmp_arr.push( this[i] ) } return tmp_arr } ASSetPropFlags( Array.prototype, [ 'copyArray' ], 7, true ); // usage _arr1 = [ 1, 2, 3, [4, 5, 6], [7, 8, 9] ] _arr2 = _arr1.copyArray()

Find and remove


//----------------------// this script remove // given data from array //----------------------//---- start script ----Array.prototype.findAndRemove = function(toRemove) { this = this.toString().split(ToRemove + ",").join("").split(","); }; //---- end script -----//---- how to use --------------------------------------b = ["pippo", "pluto", "paperone", "qui", "quo", "qua"]; trace(b) // Array before

18

b = b.findAndRemove("paperone"); trace(b) // Array after //-------------------------------------------------------

Find nearest value


/* nearest(); Author: Tony Kenny tony@kenny.net 10th January 2002 Use this function as you like. All I ask is that you leave this message in any distribution. This function take two arguments. The first being an array containing a list of values. The second a value to check. nearest() will return the *array index* of the nearest value. */ function nearest(arr, checkval) { if (arr.length <= 1) { return 0; } // must be null as zero would mean an exact match near = null; neardiff = null; for (x=0; x<arr.length; x++) { diff = Math.abs(arr[x] - checkval); //trace("Diff:"+diff); if (diff <= neardiff || neardiff == null) { neardiff = diff; near = x; } } return near; } /* end of nearest function */

Find the index of a string in array


//function by missing-link Array.prototype.findIndex=function(string){ //set the length of the array to a variable instead of keep checking it //it runs a little faster myLength=this.length; //this variable states whether we have found the index yet or not found=false; //make an incrimental variable to move through the array i=0; //now look for the first index while(i<myLength && found == false){ if(string == this[i]){ trace(i); found=true; }else{ i++; } } } //now create the basic array myArray = new Array("David", "John", "Jimmy", "Freeman"); //now call the function myArray.findIndex("John")

19
//output: 1

For-in loop
for in loop can be used to access the elements of an array.an important thing is that it read /retrieves the data from right to reft order.Example: //.................................................................. var myArray = [1,32,5265,"alok","monu","xyz"]; for( elements in myArray){ trace("elements of the array are: " + elements); } // result'll be xyz,monu,alok..... //-----------------------------------------------------------------

Get max and min values in an array


getMax = function (tmpArray) { tmpMax = 0; for (i=0; i<tmpArray.length; i++) { if (tmpArray[i]>tmpMax) { tmpMax = tmpArray[i]; } } return tmpMax; }; getMin = function (tmpArray) { tmpMin = getMax(tmpArray); for (i=0; i<tmpArray.length; i++) { if (tmpArray[i]<tmpMin) { tmpMin = tmpArray[i]; } } return tmpMin; };

Join two arrays element by element


// Join two arrays element by element //Usage: /* myArray = [0, 1, 2]; yourArray = [4, 5, 6, 3]; trace(join2array(myArray, yourArray)); 0,4,1,5,2,6,empty,3 */ function join2array(a:Array, b:Array) { var x = []; var len = a.length+b.length; for (var z = 0; z<len/2; z++) { var position1 = a[z]; var position2 = b[z]; if (position1 == undefined) { position1 = 'empty'; } if (position2 == undefined) { position2 = 'empty';

20

} x.push(position1, position2); } return x; }

Array shuffler
// This is just a shorter version of the previous. function sortRand () { return(( random(2) == 0)? -1: 1); } myArray = new Array(1,1,2,2,3,3); myArray.sort(sortRand);

numerical sorting
function sortN(arr) { var tmp = new Array(); tmp[0] = arr[0]; for ( var i=1; i<arr.length; i++ ) { num = arr[i]; var done = false; for ( var j=0; j<tmp.length; j++ ) { if ( ((num>tmp[j])&&(num<tmp[j+1])) || (num==tmp[j]) ) { tmp.splice(j+1,0,num); done = true; break; } } if ( (!done) && (num<tmp[0]) ) { tmp.unshift(num); } else if ( (!done) && (num>tmp[tmp.length-1]) ) { tmp.push(num); } } return tmp; } temp = new Array (1,25,101,23,52,52,92,4); temp = sortN(temp); trace(temp);

random number generation


//function by missing-link //Create the function Array.prototype.randomNumberGenerator=function(){ //create the limits for the numbers maxNum=10; minNum=5; range=maxNum-minNum; //the amount of random numbers to create numbers=4; //incase you ask for more numbers than are available if(numbers > ((maxNum-minNum)+1)){ numbers=(maxNum-minNum)+1; } //create needed incramental variables i=0; j=0; //these flow modifiers will create & check each number to make sure it is random while(i<numbers){

21

numArray[i]=Math.floor(Math.random()*(range+1))+minNum; while(j<i){ if(numArray[j]!=numArray[i]){ j++; }else{ //if the number is used already, it will create a new number and start over numArray[i]=Math.floor(Math.random()*(range+1))+minNum; j=0; } } //reset and increase "i" j=0; i++; } } //create the array numArray=new Array(); //run the function numArray.randomNumberGenerator(); //this will just display the array in the output window trace(numArray);

recording keystrokes into an array


onClipEvent (load) { Array.prototype.keyStrokeRecorder = function () { lastKeyPressed = String.fromCharCode (Key.getAscii()); this.push (lastKeyPressed); } var myArray = new Array (); } onClipEvent (keyDown){ myArray.keyStrokeRecorder (); } //I used the next event handler just so I can view the array onClipEvent (mouseDown) { trace (myArray); }

Remove repeated items


/ remove repeated items from an array function removeRepeated(a:Array):Array { for(var i=0; i<a.length; i++){ if(a[i] == a[i+1]){ a.splice(i, 1); removeRepeated(a); } } return a; } //usage: var myArray:Array = [0,0,1,2,2,2,3,3,5,5,5,8,8]; trace(removeRepeated(myArray)); // 0,1,2,3,5,8

22

Returns an array containing random numbers, the random numbers can be unique, they can have a range and you can specify how many random numbers you want in your array

//_root.myuniquerandomnumbers=Number.randomnumbers(10,20,10,true) Number.randomnumbers=function(lowest,highest,count,unique){ var randomnums=new Array() if(unique && count<=highest-lowest){ var nums=new Array() for(var i=lowest;i<=highest;++i){ nums.push(i) } for(var i=1;i<=count;++i){ var randomnumber=Math.floor(Math.random()*nums.length) randomnums.push(nums[randomnumber]) nums.splice(randomnumber,1) } }else{ for(i=1;i<=count;++i){ randomnums.push(lowest+Math.floor(Math.random()*(highestlowest))) } } return randomnums }

Xml to array [recursive]


xmlToArray = function (_xml) { var _arr = new Array(); for (var i=0; i<_xml.childNodes.length; i++) { switch (_xml.childNodes[i].childNodes[0].nodeType) { case 1: _arr[_xml.childNodes[i].nodeName] = xmlToArray(_xml.childNodes[i]); break; case 3: _arr[_xml.childNodes[i].nodeName] = _xml.childNodes[i].childNodes[0].nodeValue; break; } } return _arr; }

23

GENERIC FUNCTIONS Popup manager


/** * @author: Eric Feminella * @class: PopUpWindowHandler * @published: 04.04.06 * @usage: Singleton which creates and manages popup window for mxml components * @param: PopUpWindowHandler.createPopUp(target:MovieClip, classObject:Object[mxml component); */ import mx.managers.PopUpManager;

class PopUpWindowHandler { public static var popup:MovieClip; public static function createPopUp(target:MovieClip, classObject:Object):Void { if (PopUpWindowHandler.popup == null) { PopUpWindowHandler.popup = PopUpManager.createPopUp(target, classObject, false, {}); PopUpWindowHandler.popup.centerPopUp(scope); } } public static function close():Void { PopUpWindowHandler.popup.closeWindow(); PopUpWindowHandler.popup = null; } public static function get getPopUp():MovieClip { return PopUpWindowHandler.popup; } }

Transition Class
/* **************************************************************************** //name: Transition Class //description: a easy way to use mx.TransitionManager Class //made by: Carlos Queiroz //contact: carlos_queiroz@netcabo.pt //date: 04-12-2005 //update: 09-02-2006 (add events, change return obj)

24

**************************************************************************** >> available transitions transition.blinds(obj, direction:Number, duration:Number, numStrips:Number, dimension:Number, easing:Function) transition.fade(obj, direction:Number, duration:Number, easing:Function) transition.fly(obj, direction:Number, duration:Number, startPoint:Number, easing:Function) transition.iris(obj, direction:Number, duration:Number, startPoint:Number, shape:Number, easing:Function) transition.photo(obj, direction:Number, duration:Number, easing:Function) transition.pixelDissolve(obj, direction:Number, duration:Number, xSections:Number, ySection:Number, easing:Function) transition.rotate(obj, direction:Number, duration:Number, ccw:Boolean, degrees:Number, easing:Function) transition.squeeze(obj, direction:Number, duration:Number, dimension:Number, easing:Function) transition.wipe(obj, direction:Number, duration:Number, startPoint:Number, easing:Function) transition.zoom(obj, direction:Number, duration:Number, easing:Function) >> returns a mx.TransitionManager object >> events: onTransitionChanged, onTransitionFinished */ class transition { //blinds public static function blinds(obj, direction:Number, duration:Number, numStrips:Number, dimension:Number, easing:Function):Object { return (init(obj, {type:1, direction:direction, duration:duration, numStrips:numStrips, dimension:dimension, easing:easing})); } //fade public static function fade(obj, direction:Number, duration:Number, easing:Function):Object { return (init(obj, {type:2, direction:direction, duration:duration, easing:easing})); } //fly public static function fly(obj, direction:Number, duration:Number, startPoint:Number, easing:Function):Object { return (init(obj, {type:3, direction:direction, duration:duration, startPoint:startPoint, easing:easing})); } //iris public static function iris(obj, direction:Number, duration:Number, startPoint:Number, shape:Number, easing:Function):Object { return (init(obj, {type:4, direction:direction, duration:duration, startPoint:startPoint, shape:shape, easing:easing})); } //photo public static function photo(obj, direction:Number, duration:Number, easing:Function):Object { return (init(obj, {type:5, direction:direction, duration:duration, easing:easing})); } //pixelDissolve public static function pixelDissolve(obj, direction:Number, duration:Number, xSections:Number, ySection:Number, easing:Function):Object { return (init(obj, {type:6, direction:direction, duration:duration, xSections:xSections, ySection:ySection, easing:easing})); } //rotate public static function rotate(obj, direction:Number, duration:Number, ccw:Boolean, degrees:Number, easing:Function):Object { return (init(obj, {type:7, direction:direction, duration:duration, ccw:ccw, degrees:degrees, easing:easing}));

25

} //squeeze public static function squeeze(obj, direction:Number, duration:Number, dimension:Number, easing:Function):Object { return (init(obj, {type:8, direction:direction, duration:duration, dimension:dimension, easing:easing})); } //wipe public static function wipe(obj, direction:Number, duration:Number, startPoint:Number, easing:Function):Object { return (init(obj, {type:9, direction:direction, duration:duration, startPoint:startPoint, easing:easing})); } //zoom public static function zoom(obj, direction:Number, duration:Number, easing:Function):Object { return (init(obj, {type:10, direction:direction, duration:duration, easing:easing})); } // //init // private static function init(obj, specs:Object) { var tm = new mx.transitions.TransitionManager(obj); // //tm.onTransitionStarted = new Function(); tm.onTransitionChanged = new Function(); tm.onTransitionFinished = new Function(); // var listener = new Object(); // var transObj = {}; // if (specs.direction == 0) { transObj.direction = mx.transitions.Transition.IN; listener.allTransitionsInDone = function(evt:Object) { clearInterval(interval); tm.onTransitionFinished(); }; tm.addEventListener("allTransitionsInDone", listener); } else { transObj.direction = mx.transitions.Transition.OUT; listener.allTransitionsOutDone = function(evt:Object) { clearInterval(interval); tm.onTransitionFinished(); }; tm.addEventListener("allTransitionsOutDone", listener); } // transObj.duration = specs.duration; // transObj.easing = (specs.easing == undefined) ? mx.transitions.easing.None.easeNone : specs.easing; // switch (specs.type) { case 1 : //blinds transObj.type = mx.transitions.Blinds; transObj.numStrips = specs.numStrips; transObj.dimension = specs.dimension; break; case 2 :

26

//fade transObj.type = mx.transitions.Fade; break; case 3 : //fly transObj.type = mx.transitions.Fly; transObj.startPoint = specs.startPoint; break; case 4 : //iris transObj.type = mx.transitions.Iris; transObj.startPoint = specs.startPoint; transObj.shape = (specs.shape == 1) ? mx.transitions.Iris.SQUARE : mx.transitions.Iris.CIRCLE; break; case 5 : //photo transObj.type = mx.transitions.Photo; break; case 6 : //pixelDissolve transObj.type = mx.transitions.PixelDissolve; transObj.xSection = specs.xSection; transObj.ySection = specs.ySection; break; case 7 : //rotate transObj.type = mx.transitions.Rotate; transObj.degrees = specs.degrees; transObj.ccw = specs.ccw; break; case 8 : //squeeze transObj.type = mx.transitions.Squeeze; transObj.dimension = specs.dimension; break; case 9 : //wipe transObj.type = mx.transitions.Wipe; transObj.startPoint = specs.startPoint; break; case 10 : //zoom transObj.type = mx.transitions.Zoom; break; } // obj._visible = true; // tm.startTransition(transObj); //tm.onTransitionStarted(); // var interval = setInterval(function () { tm.onTransitionChanged(); }, 0); // return (tm); } } //

27

DATE FUNCTIONS Count Down


///////////first frame//////////////// today = new Date(); seconds = Math.floor((event.getTime()-today.getTime())/1000); minutes = Math.floor(seconds/60); hours = Math.floor(minutes/60); days = Math.floor(hours/24); cday = days; if (cday<10) { cday = "0"+cday; } chour = hours%24; if (chour<10) { chour = "0"+chour; } cminute = minutes%60; if (cminute<10) { cminute = "0"+cminute; } csecond = seconds%60; if (csecond<10) { csecond = "0"+csecond; } //create a dynamic text named input input = cday+" "+chour+" "+cminute+" "+csecond; // year, month -1, day, hour event = new Date(2001, 11, 31, 24);

Birthdate to Age
/*I did not like to update the page telling my age each and every year after my birthday Now I use a dynamic text field with the variable named age and this useful function*/ my_date = new Date(); function date_to_age(my_year, my_month, my_day) { mem = my_date.getTime(); my_date.setFullYear(my_year, my_month-1, my_day); myage = my_date.getTime(); mem = mem-myage; my_date.setTime(mem); trace("years/age: "+(my_date.getFullYear()-1970)+" month: "+my_date.getMonth()+" days: "+my_date.getDate()+" by www.advance-media.com"); return (my_date.getFullYear()-1970); } age = date_to_age(1970, 7, 21); /*also useful if telling your visitor for how many years your company is doing biz...e.g. No more updates needed*/

Date
function myDate () { now = new Date(year, month, date, hour, min, sec, ms); weekday = new Array("Sunday", "Monday", "Tuesday", "Wendnesday", "Thursday", "Friday", "Saturday");

28

month = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "Octobert", "November", "December"); diasemana = weekday[now.getDay()]; mes = month[now.getMonth()]; diadelmes = now.getDate(); modifier = new CreateArray(31); var modifier = new String("thstndrdthththththththththththththththththstndrdthththththththst"); var loop = 0; do { modifier[loop] = modifier.substring(loop*2, 2+(loop*2)); loop = loop+1; } while (loop<32); mySuffix = modifier[now.getDate()]; ano = now.getFullYear(); fecha_entera = weekday[now.getDay()]+" "+month[now.getMonth()]+" "+now.getDate()+mySuffix+" "+now.getFullYear(); return fecha_entera; } myDate();

Date extension class


/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Title : Author : URL : XDate Class P.J. Onori http://www.somerandomdude.net/flash_xdate.html

Description : Extension of Macromedia's Date class for Flash MX 2004+. Various methods to get more detailed date information. This class was designed for calendar-based applications and provides many useful methods to pull out all the data needed to do so. Created : Modified : 7/22/05 9/17/05

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ class pjonori.util.XDate extends Date { private var monthDays:Number private var monthWeeks:Number; private var weekArray:Array; /* Day names in various langauges (sorry, no Arabic or Eastern langauges at this point). EN SP FR GR IT */ English Spanish French German Italian

private var dayNameEN:Array = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); private var dayNameSP:Array = new Array("El Domingo", "El Lunes", "El Martes", "El Mircoles", "El Jueves", "El Viernes", "El Sbado"); private var dayNameFR:Array = new Array("Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"); private var dayNameGR:Array = new Array("Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"); private var dayNameIT:Array = new Array("Domenica", "Luned", "Marted", "Mercoled", "Gioved", "Venerd", "Sabato"); /*

29

Month names in various langauges. EN - English SP - Spanish FR - French GR - German IT - Italian */ private var monthNameEN:Array = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); private var monthNameSP:Array = new Array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"); private var monthNameFR:Array = new Array("Janvier", "Fvrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aot", "Septembre", "Octobre", "Novembre", "Dcembre"); private var monthNameGR:Array = new Array("Januar", "Februar", "Marschiert", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"); private var monthNameIT:Array = new Array("Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"); function XDate(year:Number,month:Number,date:Number,hour:Number,min:Number,sec:Number,ms:Number) { setYear(year); setMonth(month); setDate(date); this.setDaysInMonth(); this.setWeeksInMonth(); /* This class does not handle any time units lower than days at this point. setHours(hour); setMinutes(min); setSeconds(sec); setMilliseconds(ms); */ } /* * Function: * Summary: getDayOfWeek Get the day of the week (0 = Sunday, 6 = Saturday), * based on the

day of the month. * Parameters: day a day of the object's month * Return: Number (0-6) indicating the day of week */ public function getDayOfWeek(day:Number):Number { var dayBackup:Number = this.getDate(); of object's actual given date this.setDate(day); var dayOfWeek:Number = super.getDay(); this.setDate(dayBackup); //return object's day to original value return dayOfWeek; }

//create backup //set the object'

/* * Function: isSunday * Summary: Function to inidicate whether a day is Sunday * Parameters: day a day of the object's month * Return: Boolean indicating if the day is Sunday or not */ public function isSunday(day:Number):Boolean { if(this.getDayOfWeek(day)==0) { return true; } return false;

30
} /* * Function: isMonday * Summary: Read isSunday's comments for summary & details */ public function isMonday(day:Number):Boolean { if(this.getDayOfWeek(day)==1) { return true; } return false; } /* * Function: isTuesday * Summary: Read isSunday's comments for summary & details */ public function isTuesday(day:Number):Boolean { if(this.getDayOfWeek(day)==2) { return true; } return false; } /* * Function: isWednesday * Summary: Read isSunday's comments for summary & details */ public function isWednesday(day:Number):Boolean { if(this.getDayOfWeek(day)==3) { return true; } return false; } /* * Function: isThursday * Summary: Read isSunday's comments for summary & details */ public function isThursday(day:Number):Boolean { if(this.getDayOfWeek(day)==4) { return true; } return false; } /* * Function: isFriday * Summary: Read isSunday's comments for summary & details */ public function isFriday(day:Number):Boolean { if(this.getDayOfWeek(day)==5) { return true; } return false; } /* * Function: isSaturday * Summary: Read isSunday's comments for summary & details */ public function isSaturday(day:Number):Boolean { if(this.getDayOfWeek(day)==6) { return true; } return false; } /* Function: * Summary: * Parameters: * Return: isWeekend Checks to see if the day is part of the weekend day a day of the object's month Boolean indicating if the day is during the weekend

31
*/ public function isWeekend(day:Number):Boolean { if(this.getDayOfWeek(day)==6||this.getDayOfWeek(day)==0) return true; } return false; }

/* * Function: setDaysInMonth * Summary: Finds the total amount of days in the object's month * and sets 'daysInMonth' with the value */ function setDaysInMonth():Void { var tempDate = new Date(this.getYear(), this.getMonth()+1, 0); this.monthDays = tempDate.getDate(); delete tempDate; } /* * Function: * Summary: month * Return: The total number of days in the month */ function get daysInMonth():Number { return this.monthDays; } /* * Function: getDaysLeftInMonth * Summary: Returns the total number of days left in the object's month * Return: The total number of days left in the month */ function getDaysLeftInMonth():Number { return this.daysInMonth-super.getDate(); } /* * Function: getDaysInYear * Summary: Finds the total amount of days in the object's year * primarily useful to detect leap years * Return: The total number of days in the year */ function get daysInYear():Number { var daysInYear:Number=0; var i:Number=0; var year:Number=13; while(++i<year) { var tempDate = new Date(this.getYear(), i, 0); daysInYear+= tempDate.getDate(); } return daysInYear; } /* * Function: * Summary: * lands on */ function monthStartDate():Number { var dayBackup:Number = this.getDate(); this.setDate(1); var day:Number = super.getDay(); this.setDate(dayBackup); return day; } /* * Function: getMonthEndDate getMonthStartDate Finds the day (i.e Monday, Tuesday, etc.) that the first day of the object's month daysInMonth Returns the total number of days in the object's

32
* Summary: * lands on */ function monthEndDate():Number { var dayBackup:Number = this.getDate(); var lastDay:Number = this.daysInMonth; this.setDate(lastDay); var day:Number = super.getDay(); this.setDate(dayBackup); return day; } /* * Function: setWeeksInMonth * Summary: Sets the total number of weeks in the object's month */ function setWeeksInMonth():Void { monthWeeks=0; var days:Number = this.daysInMonth; var i:Number = 0; while(++i<days+1) { if(this.isSaturday(i)==true&&monthWeeks==0) { monthWeeks+=1; } else if(this.isSunday(i)==true&&i!=1) { monthWeeks+=1; } } } /* * Function: getWeeksInMonth * Summary: Gets the total number of weeks in the object's month */ function get weeksInMonth():Number { return monthWeeks; } /* * Function: getDaysInWeeks * Summary: Returns an array with the total number of days * for each week in the object's month */ function get daysInWeeks():Array { var day=1; var weekCount:Number=0; var daysCounted:Number=0; var weekArray:Array = new Array(); var days = this.daysInMonth; var i=-1; while(++i<days) { this.setDate(i+1); if(super.getDay()==6 && weekCount==0) { weekCount+=1 daysCounted = i; weekArray.push(daysCounted+1); } else if(super.getDay()==0&&i<days-7&&i!=0) weekCount+=1 weekArray.push(7); daysCounted+=7; } } weekArray.push((days-1)-(daysCounted+1)+1); return weekArray; } /* * Function: getDaysInWeek { Finds the day (i.e Monday, Tuesday, etc.) that the last day of the object's month

33
* Summary: Returns the total amount of days in a specified week * of the object's month */ function daysInWeek(week:Number):Number { var weeks:Array = this.daysInWeeks(); if(week>weeks.length||week<0) { return null; } return weeks[week]; } /* * Function: getDay * Summary: Finds the day for any date specified */ function getDay(month, year, day):Number { return (new Date(year, month, day).getDay()); } /* * Function: getDayName * Summary: Returns the name of the day specified in the language specified * Parametets: Number of days (starting w/ 0), Language of name (EN = english, FR = french, etc.) */ function getDayName(day:Number, lang:String):String { if(day>=0||day<=6) { switch(lang) { case "EN": return dayNameEN[day]; break; case "SP": return dayNameSP[day]; break; case "FR": return dayNameFR[day]; break; case "GR": return dayNameGR[day]; break; case "IT": return dayNameIT[day]; break; default : return dayNameEN[day]; break; } } else { return null } } /* * Function: getMonthName * Summary: Returns the name of the month specified in the language specified * Parametets: Number of month (starting w/ 0), Language of name (EN = english, FR = french, etc.) */ function getMonthName(month:Number, lang:String):String { if(month>=0||month<=6) { switch(lang) { case "EN": return monthNameEN[month]; break; case "SP": return monthNameSP[month]; break; case "FR": return monthNameFR[month];

34
break; case "GR": return monthNameGR[month]; break; case "IT": return monthNameIT[month]; break; default : return monthNameEN[month]; break; } } else { return null } } }

Digital clock
myDate = new Date(); timeTextField = (t = h+":"+m+":"+s); h = myDate.getHours(); m = myDate.getMinutes(); s = myDate.getSeconds(); if (s<10) { s = "0"+s; } if (m<10) { m = "0"+m; } if (h<10) { h = "0"+h; } play();

12 hour digital clock


now = new Date(); var minutes = now.getMinutes()>9 ? now.getMinutes() : "0"+now.getMinutes(); var seconds = now.getSeconds()>9 ? now.getSeconds() : "0"+now.getSeconds(); var hours = now.getHours(); if (hours > 12) { hours -= 12; myAddOn = "PM"; } else { myAddOn = "AM"; } time = hours+":"+minutes+":"+seconds+" "+myAddOn;

set number to 2 decimal places


//set number to 2 decimal places //You can set this anywhere in your timeline and use as you need anywhere in your movie.

Math.__proto__.dec2 = function (num){ valor = String (Math.round(num * 100) / 100); dot = valor.indexOf("."); if(dot == -1){ valor += ".0"; } temp = valor.split(".");

35
addDecimals = 2 - temp[1].length; for(i=1; i<= addDecimals; i++){ valor += "0"; } return valor; }; a = 0.5; b = 0.8; z = Math.dec2(5);//if you trace thism, z will display "5.00" z = Math.dec2(a + b);//if you trace thism, z will display "1.30" Round to nearest
function Round2Nearest(n) { // var floatnumber = Number(n); var Rounded = Math.round(floatnumber); var NextInt = Math.ceil(floatnumber); var PrevInt = Math.floor(floatnumber); // if ( (Math.abs(floatnumber)+ 0.5) != NextInt) { // trace(floatnumber add " >NextInt:" add NextInt); trace(floatnumber add " >PrevInt: " add PrevInt); var diff2next = (NextInt-floatnumber); var diff2prev = (floatnumber-PrevInt); trace("al prossimo intero mancano: " add diff2next); trace("all'intero precedente mancano: " add diff2next); // var Major = Math.max(diff2prev, diff2next); var IsPos = (floatnumber>0); // if (Major == diff2prev) { trace("floatnumber da chiudere all'intero precedente"); return IsPos ? PrevInt : NextInt; } else { trace("floatnumber da chiudere all'intero successivo"); return IsPos ? NextInt : PrevInt; } // } else { trace("case: 0,5 but non 0,5 periodico... ("add floatnumber add")"); return floatnumber; } } // // // // // //Usage: trace(Round2Nearest(0.000001)); trace(Round2Nearest(10.89)); trace(Round2Nearest(0.09)); trace(Round2Nearest(0.5)); trace(Round2Nearest(0.555555)); trace(Round2Nearest(0.5555551)); // this.onEnterFrame = function() { trace(Round2Nearest(Math.random())); }; stop;

format number with commas


function addCommas(theNumber){

36
numString = theNumber + ""; //convert # to string newString = ""; //return string index = 1; // string index trip = 0; // trip, as in triple. while(numString.length >= index){ if (trip!=3){ //haven't reached 3 chars yet newString = numString.charAt(numString.length - index) + newString; //add char index++; trip++; } else{ //reached 3 chars, add comma newString = "," + newString; trip=0; } } return (newString); }

Format numbers with commas efficiently


/** * Formats the given Number with commas */ public static function formatNumberWithCommas(num) { var strNum:String = num+""; if (strNum.length < 4) return strNum; return formatNumberWithCommas(strNum.slice(0, -3))+","+strNum.slice(-3); }

Random alpha numeric password generator


function generatePassword (len) { m = 0; pass = ""; alf1 = "ABCDEFGHKJILMNOPQRSTUVWXYZ"; alf2 = "1234567890"; alfabet = alf1 + alf2; alf = alfabet.length; for (m = 0; m < len; m++) { ran = Math.floor(Math.random() * (alf - 1)); pass = pass + alfabet.charAt(ran); } // end of for return pass; } new_password = generatePassword (8);

roman to Arabic
roman2arabic = function (num) { var total:Number = 0; var values:Object = {I:1, V:5, X:10, L:50, C:100, D:500, M:1000}; prev_value = 0; for (i=0; i<num.length; i++) { trace(num.charAt(i)); trace(values[num.charAt(i)]); if (values[num.charAt(i)]>prev_value) { total -= prev_value; } else { total += prev_value; }

37
prev_value = values[num.charAt(i)]; } total += prev_value; return total; }; trace(roman2arabic("IV"));

Drag and drop class


/*----------------------------------------------------------------------------------------------------------| | Author: Eric Feminella | Issued: 08.19.05 | Copyright (c)2005 www.ericfeminella.com | Class: DragnDrop | ------------------------------------------------------------------------------------------------------------/ | | Instantiate new instance of DragnDrop class as follows: | var varname:DragnDrop = new DragnDrop(dragObj, targetObj, _enabled, _alpha, _visible, _play, _mainPlay); | | | Arguments for constructor are as follows: | 1.) dragObj:Object = Object to drag | 2.) targetObj:Object = Target Object | 3.) _enabled:Boolean = Disable Drag Object | 4.) alpha:Number = Change _alpha of Drap Object | 5.) _visible:Boolean = Visibility of Drag Object | 6.) _play:Number = Drag Object - play frame number | 7.) _mainPlay:Number = Main timeline / _level - play frame number | | | Sample: | var dd:DragnDrop = new DragnDrop(this.circle, this.square, null, 80, true, null, null); | | ------------------------------------------------------------------------------------------------------------*/

class DragnDrop { private var drag:Object; private var target:Object; private static var _this:Object; private private private private private private private private private var var var var var var var var var drag_x:Number; drag_y:Number; target_x:Number; target_y:Number; enabled:Boolean; alpha:Number; visible:Boolean; dragPlay:Number; mainPlay:Number;

// constructor for DragnDrop class - dragObj, targetObj, _enabled, _alpha, _visible, _play, _mainPlay function DragnDrop(dragObj:Object, targetObj:Object, _enabled:Boolean, alpha:Number, _visible:Boolean, _play:Number, _mainPlay:Number) { DragnDrop._this = this;

38
this.drag = dragObj; this.target = targetObj; this.drag_x = dragObj._x; this.drag_y = dragObj._y; this.target_x = targetObj._x; this.target_y = targetObj._y; this.enabled = _enabled; this.alpha = alpha; this.visible - _visible; this.dragPlay = _play; this.mainPlay = _mainPlay; build(); } private function build():Void { this.drag.onPress = function() { DragnDrop._this.Drag(); }; this.drag.onRelease = function() { DragnDrop._this.Drop(); }; } private function Drag():Void { this.drag.startDrag(); } private function Drop():Void { this.drag.stopDrag(); if (eval(this.drag._droptarget) == this.target) { this.drag.enabled = this.enabled; this.drag._alpha = this.alpha; this.drag.gotoAndPlay(this.dragPlay); this.drag._visible = this.visible; this.drag._x = this.target_x; this.drag._y = this.target_y; gotoAndStop(mainPlay); } else { this.drag._x = this.drag_x; this.drag._y = this.drag_y; } } }

39

Trace Object Class


/** * @author: Eric Feminella * @version 1.1 * @copyright: http://www.ericfeminella.com */ package { public final class TraceObject { public static function filterObject(obj:Object, recursivelyTraceAll:Boolean):void { if (obj is Array) { if (obj[0] != null) { e.trace("\nObject is of Type: Array[Indexed]\nIndexed as follows:"); for (var i:Number = 0; i < obj.length; i++) { if (obj[i] is Object || obj[i] is Array) { if (recursivelyTraceAll) { TraceObject.filterObject(obj[i], true); } else { e.trace("\t[" + i + "] = " + obj[i] + ""); } } else { e.trace("\t[" + i + "] = " + obj[i] + ""); } } } else { e.trace("\nObject is of Type: Array[Associative]\nKeyed as follows:"); for (var element:* in obj) { if (element is Object || element is Array) { if (recursivelyTraceAll) { TraceObject.filterObject(element, true); } else { e.trace("\t['" + element + "'] = " + obj[element]);

40
} } else { e.trace("\t['" + element + "'] = " + obj[element]); } } } } else if (obj is Object) { e.trace("\nObject is of Type: " + typeof(obj)); for (var prop:* in obj){ if (prop is Object || prop is Array) { if (recursivelyTraceAll) { TraceObject.filterObject(prop, true); } else { e.trace("\t\t." + prop + " = " + obj[prop]); } } else { e.trace("\t\t." + prop + " = " + obj[prop]); } } } else if (obj == null) { e.trace("A type of undefined has been set for: " + obj); } } } }

Bad word filter


// Function filters the wanted words ourt of the text // http://flash.andihaas.de String.prototype.changer = function(fil) { var a = this; var i, r, b; for (i in fil) { b = "xxx"; for (r=0; r<fil[i].length; r++) { a = a.split(fil[i]).join(b); } } t = a.indexOf("x"); t == -1 ? trace("no hits") : trace("results !!"); return a; }; word = ["badguy", "bastard", "goofy"]; x = "goofy was in town an met the badgy gringo. he wa s a real bastard"; trace(x.changer(word));

random names
//random letters

41
//this ones kinda old function rCons(myLetter):String { var cArray:Array = new Array("b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "qu", "r", "s", "t", "v", "w", "x", "y", "z", "z"); var aNum:Number = new Number(Math.ceil(random(22))); myLetter = cArray[aNum]; return (myLetter); } function rVowels(myLetter):String { var vArray:Array = new Array("a", "e", "i", "o", "u","u"); var bNum:Number = new Number(Math.ceil(random(6))); myLetter = vArray[bNum]; return (myLetter); } function genName(myExt, myString):String { var nNum2:Number = new Number(Math.floor(random(4)+3)); var nText:String = new String(""); for (i=0; i<nNum2; i++) { var tempNum1:String = rCons(); var tempNum2:String = rVowels(); nText += tempNum1; nText += tempNum2; } myString = nText; myString += myExt; return (myString); } // example 1 var nTt:String = genName("_mc"); //returns "randomName_mc" // example 2 var nT2:String = genName(""); //returns "randomName"

Word count or syntax remover


notToCount = [",","?",";",".",":","/","!","%","$","+","=",")","]"," \\","|","","{","'","#","\"","~","&","","<",">"," ","*"," "]; function replace(str,byStr,fromStr){ while(fromStr.indexOf(str) ne -1){ fromStr = fromStr.substr(0,fromStr.indexOf(str)) add byStr add fromStr.substr(fromStr.indexOf(str)+str.length); } return fromStr; } function countWords(thing){ nbWords = 0; for(a=0;a<notToCount.length;a++){ thing = replace(notToCount[a]," ",thing); } if(thing.substr(thing.length-1) == " "){ thing.length-=1; } for(a=0;a<thing.length;a++){ if(thing.substr(a,1) == " "){ nbWords++; } } return nbWords; } trace(countWords(_root.chose)); //vive Jsus

Word counting
//count number of word that seperate by space bar or/and enter(\r) function countMe(myString) {

42
sentence = ""; itemlist = myString.split("\r"); for (n=0; n<itemlist.length; n++) { (itemlist[n] == "") ? sentence += " " : sentence += " "+itemlist[n]; } word = 0; itemlist = sentence.split(" "); for (n=0; n<itemlist.length; n++) { if (itemlist[n] != "") { word++; } } return word; } trace(countMe(myField.text)); trace(countMe(myVar))

is Prime
/* Number.prototype.isPrime() Helps dealing with the oldest of math troubles: testing number primitivity. usage syntax: variable.isPrime(); */ Number.prototype.isPrime = function() { if (this > 2 && this % 2 == 0) return false; for (var i = 3, l = Math.sqrt(this); i <= l; i += 2) if (this % i == 0) return false; return true; }

Tooltip class
/** * Tooltip Button * * - generates a mouse over tool tip * * Flash Player 6 * Actionscript 2.0 * * * @Author: Christopher Couchoud * * @Version: 1.0 * * * @To do's * * */ class Tooltip { // reference to this object private var thisObj:Tooltip; // tip movieclip holder private var text_mc:MovieClip; // tooltip textfield private var tooltip_txt:TextField; // tooltip shadow

43
private var shadow_mc:MovieClip; // tip text private var tip:String; // constructor function Tooltip(t:String) { thisObj = this; tip = t; createToolTip(); } /** * * CreateToolTip * - creates the tooltip * * */ private function createToolTip(Void):Void { var thisObj:Tooltip = this; // trace("creating tool tip"); // create tooltip holder - send it way below for now text_mc = _level0.createEmptyMovieClip("text_holder", 15000, {_x:0, _y:0}); // move text_mc - must be done after initialization to make sure the text appears where its supposed to text_mc._x = _level0._xmouse; text_mc._y = _level0._ymouse; // create text field for tip text_mc.createTextField("tooltip_txt", 10, tooltip_txt = text_mc.tooltip_txt; // set text field parameters tooltip_txt.html = true; tooltip_txt.backgroundColor = 0xFFFFEE; tooltip_txt.background = true; tooltip_txt.border = true; tooltip_txt.borderColor = 0x666666; tooltip_txt.autoSize = "left"; tooltip_txt.multiline = false; tooltip_txt.wordWrap = false; tooltip_txt.textColor = 0x333333; tooltip_txt.selectable = false; // set text tooltip_txt.htmlText = this.tip; // add formatting var theFormat:TextFormat = new TextFormat(); theFormat.font = "Verdana"; theFormat.size = 10; theFormat.rightMargin = 5; // set the format tooltip_txt.setTextFormat(theFormat); // draw the shadow 0, 21, 20, 20);

44
drawShadow(); // have it move onEnterFrame text_mc.onEnterFrame = function() { thisObj.moveToolTip(); } } /** * moveToolTip * - posistions the tooltip and shadow based on cursor posistion * */ public function moveToolTip(Void):Void { text_mc._x = _level0._xmouse; text_mc._y = _level0._ymouse; } /** * drawShadow * - creates shadow below tooltip * */ public function drawShadow(Void):Void { // create shadow holder shadow_mc = text_mc.createEmptyMovieClip("shadow_mc", 1, {_x:1, _y:22, _alpha:0}); // create a starting shadow shape var sdow:MovieClip = shadow_mc.createEmptyMovieClip("sdow", 50); sdow.beginFill(0x000000, 100); sdow.moveTo(tooltip_txt._x, tooltip_txt._y) sdow.lineTo(tooltip_txt._x, tooltip_txt._y); sdow.lineTo(tooltip_txt._x + tooltip_txt._width, tooltip_txt._y); sdow.lineTo(tooltip_txt._x + tooltip_txt._width, tooltip_txt._y + tooltip_txt._height); sdow.lineTo(tooltip_txt._x, tooltip_txt._y + tooltip_txt._height); sdow.lineTo(tooltip_txt._x, tooltip_txt._y); sdow.endFill(); // duplicate the clip for(var i:Number = 0; i <= 4; i++) { // trace("should be duplicating"); sdow.duplicateMovieClip("c" + i, 10 - i,{_alpha:7, _x:sdow._x + i, _y:sdow._y + i}); } } /** * destroy * - removes the tooltip * */ public function destroy(Void):Void { // trace("should be destroying the tooltip");

45
text_mc.removeMovieClip(); } }

Array Collection filter function


public function excludeEmpties( { if( item == null || item == { return false; // exclude } return true; // include the } item:Object ):Boolean "" ) the item item

// set the filter function on the collection public function applyFilter():void { this.collection.filterFunction = excludeEmpties; // call refresh to update the collection's "view" this.collection.refresh(); }

Flex 4.5 Center of Stage


popUp.width = FlexGlobals.topLevelApplication.width - 40; //popup - leave side edges popUp.height = FlexGlobals.topLevelApplication.height - 40; //popup - leave top + bottom edges popUp.x = FlexGlobals.topLevelApplication.width/2 - popUp.width/2; //popup x coord popUp.y = FlexGlobals.topLevelApplication.height/2 - popUp.height/2; //popup y coord

Array Collection to XML


/** * The below two functions are used to convert array collection to xml */ private function arrCol2XML( arrCol:ArrayCollection ):XML { var xml:XML = new XML( <Root></Root> ); for ( var i:Number = 0; i < arrCol.length; i++ ) { var obj:Object = arrCol.getItemAt( i ); xml.appendChild( recursive( obj )); } return xml; }

46

private function recursive( obj:Object, str:String = 'Record' ):XML { var xml:XML = new XML( '<' + str + '></' + str + '>' ); xml.appendChild( xml.appendChild( xml.appendChild( xml.appendChild( xml.appendChild( xml.appendChild( xml.appendChild( xml.appendChild( xml.appendChild( xml.appendChild( )); xml.appendChild( XML( "<Field11>" + obj.Field11.toString() + "</Field11>" )); xml.appendChild( XML( "<Field12>" + obj.Field12.toString() + "</Field12>" )); xml.appendChild( XML( "<Field13>" + obj.Field13.toString() + "</Field13>" )); xml.appendChild( XML( "<Field14>" + obj.Field14.toString() + "</Field14>" )); xml.appendChild( XML( "<Field15>" + obj.Field15.toString() + "</Field15>" )); xml.appendChild( XML( "<Field16>" + obj.Field16.toString() + "</Field16>" )); xml.appendChild( XML( "<Field17>" + obj.Field17.toString() + "</Field17>" )); xml.appendChild( XML( "<Field18>" + obj.Field18.toString() + "</Field18>" )); return xml; } XML( XML( XML( XML( XML( XML( XML( XML( XML( XML( "<Field1>" + obj.Field1.toString() + "<Field2>" + obj.Field2.toString() + "<Field3>" + obj.Field3.toString() + "<Field4>" + obj.Field4.toString() + "<Field5>" + obj.Field5.toString() + "<Field6>" + obj.Field6.toString() + "<Field7>" + obj.Field7.toString() + "<Field8>" + obj.Field8.toString() + "<Field9>" + obj.Field9.toString() + "<Field10>" + obj.Field10.toString() "</Field1>" )); "</Field2>" )); "</Field3>" )); "</Field4>" )); "</Field5>" )); "</Field6>" )); "</Field7>" )); "</Field8>" )); "</Field9>" )); + "</Field10>"

Unique Array Collection Values


private function uniqueACValues( myAC:ArrayCollection ):ArrayCollection { var var var var var var unique:Object = {}; value:String; array:Array = myAC.toArray(); result:Array = []; i:int = 0; n:int = array.length;

for ( i; i < n; i++ ) { value = array[ i ].adId; if ( !unique[ value ]) { unique[ value ] = true; result.push( value );

47

} } return new ArrayCollection( result ); }

Convert XML TO ArrayCollection


import mx.utils.ArrayUtil; import mx.rpc.xml.SimpleXMLDecoder; import mx.collections.ArrayCollection; private function convertXmlToArrayCollection( file:String ):ArrayCollection { var xml:XMLDocument = new XMLDocument( file ); var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(); var data:Object = decoder.decodeXML( xml ); var array:Array = ArrayUtil.toArray( data.rows.row ); return new ArrayCollection( array ); }

Vous aimerez peut-être aussi