<cffunction name="arrayFoldLeft" access="public" returntype="any" output="false" hint="I fold a product across the length of an array from 1 to N."> <!--- Define arguments. ---> <cfargument name="array" type="array" required="true" hint="I am the array over which we are performing the foldLeft action." /> <cfargument name="initialProduct" type="any" required="false" hint="I am the initial value that gets passed as the product to the first array index." /> <cfargument name="operator" type="any" required="true" hint="I am the binary operator that will be applied to each array value. I take the current product and the current value." /> <!--- Define the local scope. ---> <cfset var local = {} /> <!--- Start out with our product if the initial product is available. If not, then we'll just leave the local product undefined. ---> <cfif !isNull( arguments.initialProduct )> <!--- Set the initial local product. ---> <cfset local.product = arguments.initialProduct /> </cfif> <!--- Loop over each array index and apply the given operator to the value at the current index. ---> <cfloop index="local.value" array="#arguments.array#"> <!--- Check to see if the product is currently available. If not, we need to explicitly pass NULL into the operator since we can't refer to a null value directly. ---> <cfif isNull( local.product )> <!--- Padd in a null product. ---> <cfset local.product = arguments.operator( javaCast( "null", "" ), local.value ) /> <cfelse> <!--- Pass in the current product. ---> <cfset local.product = arguments.operator( local.product, local.value ) /> </cfif> </cfloop> <!--- Return the aggregated product. Check to see if it is null. If it is, we need to return Void. ---> <cfif isNull( local.product )> <!--- Return void. ---> <cfreturn /> <cfelse> <!--- Return the product. ---> <cfreturn local.product /> </cfif> </cffunction> <!--- ----------------------------------------------------- ---> <!--- ----------------------------------------------------- ---> <!--- ----------------------------------------------------- ---> <!--- ----------------------------------------------------- ---> <!--- Build up an array of numbers. ---> <cfset numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] /> <!--- Now, get the multiplication product of all the numbers in the array (ie. what is the value of all the numbers in the array being multiplied together). ---> <cfset product = arrayFoldLeft( numbers, 1, <function( currentProduct, value ){ <!--- Multiple the current product by the given value. ---> <cfreturn( currentProduct * value ) /> }> ) /> <!--- Output the product. ---> <cfoutput> Product of Multiplication: #product# </cfoutput>