devbox@COMPUTEC The Computec development blog

16Apr/100

ColdFusion UDF to intersect two lists

Just a quick one: I have a method that takes a list argument; there is a discrete list of legal values for this list. I want to filter the passed argument list by throwing out all the values which are not contained in the list of legal values.

Of course I could use a nested loop to do this - but for longer lists this is neither fast nor elegant. Again I'll turn to Java for this. ColdFusion's arrays are in fact java.util.Lists, so after converting our ColdFusion lists to ColdFusion arrays, we can make use of the Java-API for lists.

Here's a quick UDF that does what I want:

<cffunction name="listIntersect" output="no" returntype="string" 
	hint="returns values from list 1 which are contained in list 2">
	<cfargument name="lstSand" type="string" required="yes" />
	<cfargument name="lstSieve" type="string" required="yes" />
	<cfargument name="chDelimiter" type="string" required="no"
		    default="," />
	<cfscript>
	var aLstSand  = listToArray(arguments.lstSand,arguments.chDelimiter);
	var aLstSieve = listToArray(arguments.lstSieve,arguments.chDelimiter);
	aLstSand.retainAll(aLstSieve);
	return arrayToList(aLstSand,arguments.chDelimiter);
	</cfscript>
</cffunction>

Usage:

<cfset lstSand   = 'foo,bar,illegalparam,whatever' />
<cfset lstSieve  = 'bar,foo,someotherval,whatever' />
<cfset lstSieved = listIntersect(lstSand,lstSieve) />
<cfoutput>#lstSieved#</cfoutput>

This will output foo,bar,whatever.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.