1
\$\begingroup\$

This function converts a list to an array when list has quotes and embedded comma:

array function convertRow(required string lstRow) {

    var arResult = [];
    var arTemp = ListToArray(arguments.lstRow, ',', true);

    var quoteMode = false;
    var startQuote = false;

    for (var i in arTemp) {

        if (i CONTAINS '"' && not quoteMode) { startQuote =  true; }

        if (startQuote) {
            ArrayAppend(arResult, replace(i, '"', ''));

            startQuote = false;
            quoteMode = true;
        }
        else if (quoteMode) {
            arResult[ArrayLen(arResult)] &= "," & replace(i, '"', '');

            if (i CONTAINS '"') quoteMode = false;
        }
        else
            ArrayAppend(arResult, i);
    }

    writedump(lstRow);
    writedump(arResult);

    return arResult;
}
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

I could get rid of your startQuote variable, I reduced the number of i CONTAINS '"' comparasions by 1.

array function convertRow(required string lstRow) {
    var arResult = [];
    var arTemp = ListToArray(arguments.lstRow, ',', true);
    var quoteMode = false;

    for (var i in arTemp) {
        var containsQuote = i CONTAINS '"';
        if (containsQuote && not quoteMode) {
            ArrayAppend(arResult, replace(i, '"', ''));
            quoteMode = true;
        }
        else if (quoteMode){
            arResult[ArrayLen(arResult)] &= "," & replace(i, '"', '');
            quoteMode = not containsQuote;
        }
        else{
            ArrayAppend(arResult, i);
        }
    }


    writedump(lstRow);
    writedump(arResult);

    return arResult;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.