cfml

How to calculate summation of square of numbers in array in CFML


I am solving kata on codewars. Simple challenge, but I struggle to debug my CFML code.

Task is to square each number in array numbers and return summation of these squares.

Here is my solution:

component {
    numeric function squareSum(required Array numbers) {
        numeric result = 0;
        for (numeric i = 1; i <= arrayLen(numbers); i++) {
            result = result + (numbers[i] * numbers[i]);
        }
        return result;
    }
}

and here is the error:

template:Missing [;] or [line feed] after expression:

Solution

  • Coldfusion is not a strongly typed language. So numeric is not needed on the variable definition. But function return type numeric is allowed.

    component {
        numeric function squareSum(required Array numbers) {
            result = 0;
            for (i = 1; i <= arrayLen(numbers); i++) {
                result = result + (numbers[i] * numbers[i]);
            }
            return result;
        }
    }
    

    DEMO