Saturday, October 12, 2013

ArrayEach() And StructEach() In ColdFusion 10

Today I was looking into new functions added ColdFusion 10 and I found two interesting functions. So, I thought to share those functions.

-        ArrayEach()
-        StructEach()

1.      ArrayEach(array, HandlerFunction( Any currentObj){})

“ArrayEach” is used to loop over an array object and the Handle Function can have each element of the  array during looping. So, we can apply our business logic in side the handler function. We can write the handler function as inline function or a named function which we can reuse in multiple cases.

Lets see the example:

<cfscript>
       dispObj = new Display();
       arr = [1,2,3,4,5,6,7,8,9,10];
       WriteDump(arr);

       function showArrayElement( elem ) {
              Writeoutput(elem & '<br>');
       }

       //Calling an inline function during loop over an array
       arrayEach(arr, function(currentObj) { Writeoutput( currentObj & '<br/>' ); });

       //Calling a named function during looping over the array
       arrayEach(arr, showArrayElement);

       //Calling a named function by object during looping over the array
       arrayEach(arr, dispObj.showArrayElem);
</cfscript>
After running the above code I got the following output.


2.  StructEach( structure,  HandlerFunction( key, value ) {})

Similarly like AyyayEach() here we can loop over a structure elements where the handle function have the key and value. Using the handler function we can implement our business logic.

Lets see the code:

<cfscript>
       dispObj = new Display();
       struct = {name: "Upendra", place: "Hyderabad", technology: "coldfusion", time: "12:53PM"};
       Writedump(struct);

       function showStructElement(key, value) {
              Writeoutput( key & ':' & value & '<br/>' );
       }

       //Calling an inline function while looping over the struct
       structEach( struct, function(key, value) { Writeoutput( key & ':' & value & '<br/>' ); } );


       //Calling a named function during looping over a structure
       structEach( struct, showStructElement );

       //Calling a named function by object during looping over a structure
       structEach( struct, dispObj.showStructElement );
</cfscript>
After running above code we will get the following output:


***NOTE: In the output I have not displayed the result of named function call by creating object of a component as it would produce same result as general named function call.

Display.cfc

component output="true"{

       function showArrayElem( elem) {
              Writeoutput(elem & '<br>');
       }

       function showStructElement(key, value) {
              Writeoutput( key & ':' & value & '<br/>' );
       }

}

No comments:

Post a Comment

Followers