CFLib.org – Common Function Library Project

ListSwap(list, positionA, positionB[, delims])

Last updated June 21, 2002

author

Rob Baxter

Version: 1 | Requires: CF5 | Library: StrLib

Description:
ListSwap(list, A, B) will swap the list element at position A and the list element at position B and return a new list with the swapped elements. If either position is not a valid element in the string, the original list is returned. The fourth (optional) argument to the UDF is the delimiter definition for the list (default is ",").

Return Values:
Returns a string.

Example:

<cfset list = "a,bb,ccc,dddd,eeeee,ffffff,ggggggg,hhhhhhh,iiiiiiiii,kkkkkkkkkk">
<cfoutput>
original list = #list#<br>
swap positions 3 and 4 = #listswap(list, 3, 4)#
</cfoutput>

Parameters:

Name Description Required
list The list to modify. Yes
positionA The first position to swap. Yes
positionB The second position to swap. Yes
delims The delimiter to use. Defaults to a comma. No

Full UDF Source:

/**
 * Swaps two elements in a list.
 * 
 * @param list      The list to modify. (Required)
 * @param positionA      The first position to swap. (Required)
 * @param positionB      The second position to swap. (Required)
 * @param delims      The delimiter to use. Defaults to a comma. (Optional)
 * @return Returns a string. 
 * @author Rob Baxter (rob@microjuris.com) 
 * @version 1, June 21, 2002 
 */
function ListSwap(list, PositionA, PositionB)
{
    var elementA = "";
    var elementB = "";
    var Delims = ",";

    if (ArrayLen(Arguments) gt 3)
        Delims = Arguments[4];
            
    if (PositionA gt ListLen(list) Or PositionB gt ListLen(list) Or PositionA lt 1 or PositionB lt 1)
        return list;    
    
    elementA = ListGetAt(list, PositionA, Delims);
    elementB = ListGetAt(list, PositionB, Delims);
    
    //do the swap
    list = ListSetAt(list, PositionA, elementB, Delims);
    list = ListSetAt(list, PositionB, elementA, Delims); 

    return list;
}

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