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;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson