Search code examples
recursioncoldfusioncfmlcoldfusion-2016

structs with structs and booleans


I have a variable that consists structs. These structs can have CFBoolean variables, more structs, and other variables. In the beginning this was nested two levels deep. We are now moving up to four levels. I don't like my current approach. I could also imagine five levels happening. I have no control over the external system that needs this data. So I am looking for a more general approach.

function toJavaBoolean(any data){
    //for now, assume it's a struct to DBO conversion

    data.each(function(key, value) {
        if (getMetadata(data[key]).getName() == 'coldfusion.runtime.CFBoolean') {
            data[key] = javacast("boolean", data[key]);
        }

        if (isStruct(data[key]))    {
            data2 = data[key];
            data2.each(function(key, value) {
                if (getMetadata(data2[key]).getName() == 'coldfusion.runtime.CFBoolean')    {
                    data2[key] = javacast("boolean", data2[key]);
                }

                if (isStruct(data2[key]))   {
                    data3 = data2[key];
                    data3.each(function(key, value) {
                        if (getMetadata(data3[key]).getName() == 'coldfusion.runtime.CFBoolean')    {
                            data3[key] = javacast("boolean", data3[key]);
                        }

                        if (isStruct(data3[key]))   {
                            data4 = data3[key];
                            data4.each(function(key, value) {
                                if (getMetadata(data4[key]).getName() == 'coldfusion.runtime.CFBoolean')    {
                                    data4[key] = javacast("boolean", data4[key]);
                                }
                            });
                        }
                    });
                }
            });
        }
    });

Solution

  • You can use recursion like so...

    function toJavaBoolean(any data){
        data.each(function(key, value) {
            if (getMetadata(data[key]).getName() == 'coldfusion.runtime.CFBoolean') {
                data[key] = javacast("boolean", data[key]);
            }
            else if (isStruct(data[key]))
                data[key] = toJavaBoolean(data[key]);
        }
        return data;
    }
    

    There are some non-recursive approaches that may be faster for larger sizes or great depths.