Empowering Smart Business (sm)

UDFs: formatListAsSeries()

The future of your business is an open road, JPG image (20.8kb)

formatListAsSeries()

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.

<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
 * @version 1, June 4, 2004
 */
function formatListAsSeries(theList) {
  var lastEle = "";
  var isSet = false;
  var fList = "";
  var currEle = "";
  var idx = 0;

  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>

This UDF is also available from cflib.org at http://www.cflib.org/udf/formatListAsSeries.