Railo 4 supports closures (a.k.a. anonymous functions) in ColdFusion.
I’ve been playing with the different ways of using them in the various apps I am building at Straker Translations.
Today there was a need to loop over the keys of a structure (a.k.a. associative arrays) and add the value of all the keys.
The usual idiom of regular ColdFusion code would be to use <cfloop> to go over all the keys and do the addition.
With Railo closures it is much simpler. Here is the code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<cfscript> | |
// this is the collection we want to loop over and add all the keys | |
numbers = { "num1" : 3, "num2" : 4} | |
// setup a variable to hold the sum of the value of all the keys | |
sum = 0 | |
// closure magic | |
numbers.each( function(k,v){ | |
return sum+= v; | |
}) | |
</cfscript> |
It is simple and elegant. Makes the code much more succinct and powerful.