CFLib.org – Common Function Library Project

arrayMap(array, f)

Last updated June 23, 2014

author

Henry Ho

Version: 1 | Requires: CF9 | Library: DataManipulationLib

Description:
ArrayMap is introduced in CF11 but it is quite easy to make it available for CF10.

Return Values:
Returns a new array, with each element mapped by the callback

Example:

// TestQueryGetRow.cfc
component extends="testbox.system.BaseSpec" {

	function run(){
		include "udfs/arrayMap.cfm";
		var testArray  = ["tahi","rua","toru","wha"];

		describe("Tests arrayMap()", function(){
			it("handles an empty array", function(){
				expect(
					_arrayMap([], function(v,i,a){
						return v;
					})
				).toBe([]);
			});
			it("handles a direct transformation", function(){
				expect(
					_arrayMap(testArray, function(v,i,a){
						return v;
					})
				).toBe(testArray);
			});
			it("handles an actual transformation", function(){
				var newArray =_arrayMap(testArray, function(v,i,a){
					return ucase(v);
				}); 
				expect(
					newArray.toList()
				).toBeWithCase("TAHI,RUA,TORU,WHA");
			});
		});
	}

}

Parameters:

Name Description Required
array Array to map Yes
f Callback with which to map each element Yes

Full UDF Source:

/**
 * arrayMap() for CF9/10
 * v0.9 by Henry Ho
 * v1.0 by Adam Cameron (converting to script)
 * 
 * @param array 	 Array to map (Required)
 * @param f 	 Callback with which to map each element (Required)
 * @return Returns a new array, with each element mapped by the callback 
 * @author Henry Ho (henryho167@gmail.com) 
 * @version 1, June 23, 2014 
 */
array function arrayMap(required array array, required any f){
	if (!isCustomFunction(f)){
		throw(type="InvalidArgumentException", message="The 'f' argument must be a function");
	}

	var result	= [];
	var arrLen	= arrayLen(array);
	for (var i=1; i <= arrLen; i++){
		arrayAppend(result, f(array[i], i, array));
	}
	return result;
}
blog comments powered by Disqus

Search CFLib.org


Latest Additions

Kevin Cotton added
date2ExcelDate
May 5, 2016

Raymond Camden added
CapFirst
April 25, 2016

Chris Wigginton added
loremIpsum
January 18, 2016

Gary Stanton added
calculateArrival...
November 19, 2015

Sebastiaan Naafs - van Dijk added
getDaysInQuarter
November 13, 2015

Created by Raymond Camden / Design by Justin Johnson