Monday, February 20, 2012

Using ColdFusion 10's Function Data Type To Create a Map Function

In functional programming a map function is a way to create an array by passing each element of the array into a function.  Mapping functions are very commonly used in languages like Ruby, Python and JavaScript.  ColdFusion acts more like JavaScript in this respect where a Map is not a native function, however it is easy to implement.

Before I get into the code, lets take a look at how the map function works.   The method signature for map looks like this: public Array function map(Array arr, function fn). The map function takes and array and a function as parameters, and returns an array.  Each element in the array argument is passed into the function and the result is added to the result.

Without further adu, lets take a look a the code:

Running this code would produce this result:

Now this pattern can be applied anywhere you find yourself looping through an array and applying the same logic to each member of the array.
Fork me on GitHub