CFLib.org – Common Function Library Project

formatListAsSeries(theList)

Last updated January 14, 2010
Download UDF

author

Mosh Teitelbaum Mosh Teitelbaum

Version: 2 | Requires: ColdFusion 5 | Library: StrLib

 
Rated 0 time(s). Average Rating: 0

Description:
Function that formats a numeric list so that successive numbers are shown as a series. List must be numeric. For this function to be useful, list elements should be sorted in ascending order. Updated 1/14/10 by Todd Sharp (todd@cfsilence.com) to sort the list before grouping.

Return Values:
Returns a string.

Example:

<cfoutput>
#formatListAsSeries("2,1,6,4,7,8,10")#
<!--- outputs: 1-2, 4, 6-8, 10 --->
</cfoutput>

Parameters:

Name Description Required
theList The list to parse. Yes

Full UDF Source:

<cfscript>
/**
* Function that formats a numeric list so that successive numbers are shown as a series.
*
* @param theList      The list to parse. (Required)
* @return Returns a string.
* @author Mosh Teitelbaum (mosh.teitelbaum@evoch.com)
* @version 2, January 14, 2010
*/

function formatListAsSeries(theList) {
var lastEle = "";
var isSet = false;
var fList = "";
var currEle = "";
var idx = 0;
    
    theList = listSort(theList, "numeric", "asc");
    
    for ( idx = 1; idx LTE ListLen(theList); idx = idx + 1 ) {
        currEle = ListGetAt(theList, idx);
        
        if ( Len(lastEle) EQ 0 ) {
            fList = fList & currEle;
            lastEle = currEle;
            isSet = false;
        } else if ( lastEle EQ currEle ) {
            //do nothing
        } else if ( lastEle + 1 NEQ currEle ) {
            if ( isSet ) {
                fList = fList & lastEle;
            }
            fList = fList & ", " & currEle;
            lastEle = currEle;
            isSet = false;
        } else {
        if ( NOT isSet ) {
            fList = fList & "-";
        }
        lastEle = currEle;
        isSet = true;
        }
    }

    if ( isSet ) {
        fList = fList & lastEle;
    }

    return fList;
}
</cfscript>

Search CFLib.org


Latest Additions

Ryan Thompson-Jewell Ryan Thompson-Jewell added
ListSplit
13 hour(s) ago

Nathan Dintenfass Nathan Dintenfass added
RowsToColumns
13 hour(s) ago

Barney Boisvert Barney Boisvert added
indentXml
23 hour(s) ago

Barney Boisvert Barney Boisvert added
REReplaceCallbac...
23 hour(s) ago

Top Rated

Rob Brooks-Bilson                                 FolderSize
Rated 5.0, 7 time(s)

Nick Giovanni                                     UniqueValueList
Rated 5.0, 5 time(s)

James Sleeman                                     QuickSort
Rated 5.0, 3 time(s)

Stephen Withington RandomizeString
Rated 5.0, 3 time(s)

Created by Raymond Camden / Design by Justin Johnson