Thursday 25 July 2013

CFML implementation of Array.reduce()

G'day:
I've knocked out a quick arrayReduce() UDF, which I'll post on CFLib once I get some code review feedback (if any) on it. I'd appreciate sets of eyes on it, if you had time.

Update:
Adam Tuttle (only one mention today mate, sorry) offered some advice on Code Review, which I have taken onboard. This is the second iteration of the function. I have also updated the entry on Code Review too.

For the sake of completeness, here's the code, but pls feed-back on the Code Review page, as per link above:

/**
* @hint CFML implementation of Array.reduce(), similar to Javascript's one ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
* @array Array to reduce
* @callback Callback function to use to reduce. Will receive the following arguments: element (of current iteration of the all), index, array, (optional) result (of preceeding call to callback())
* @initialValue The initial value to use to start the reduction
*/
any function arrayReduce(required array array, required any callback, any initialValue){
    var startIdx = 1;
    if (!structKeyExists(arguments, "initialValue")){
        if (arrayLen(array) > 0){
            var result = callback(array[1], 1, array);
            startIdx = 2;
        }else{
            return;
        }
    }else{
        var result = initialValue;
    }
    for (var i=startIdx; i <= arrayLen(array); i++){
        result = callback(array[i], i, array, result);
    }
    return result;
}

If created a Gist with full(-ish) unit test coverage, too.

Ta.

--
Adam