Utility Functions: StructToListPairs() and ListPairsToStruct()
- January 17, 2009 5:30 AM
- Utility Function
- Comments (0)
Today we have a pair of functions designed to convert structures into list pairs and back again. They serve as the back bone of another pair of functions that I'll release soon. StructToListPairs() is also useful when constructing long links (such as creating "sort" links for tables).
<cffunction name="StructToListPairs" returntype="string">
<cfargument name="struct" type="struct" requried="true" />
<cfargument name="delimiter1" type="string" required="false" default="&" />
<cfargument name="delimiter2" type="string" required="false" default="=" />
<cfset var buffer = CreateObject("java", "java.lang.StringBuffer").init() />
<cfloop collection="#arguments.struct#" item="key">
<cfset buffer.append(key) />
<cfset buffer.append(delimiter2) />
<cfset buffer.append(arguments.struct[key]) />
<cfset buffer.append(delimiter1) />
</cfloop>
<cfif buffer.length() gt 1>
<cfset buffer.setLength(buffer.length()-1) />
</cfif>
<cfreturn buffer.toString() />
</cffunction>
<cffunction name="ListPairsToStruct" returntype="struct">
<cfargument name="list" type="string" requried="true" />
<cfargument name="delimiter1" type="string" required="false" default="&" />
<cfargument name="delimiter2" type="string" required="false" default="=" />
<cfset var returnValue = StructNew() />
<cfloop list="#arguments.list#" index="pair" delimiters="#arguments.delimiter1#">
<cfset returnValue[ListFirst(pair, arguments.delimiter2)] = ListLast(pair, arguments.delimiter2) />
</cfloop>
<cfreturn returnValue />
</cffunction>
<cfargument name="struct" type="struct" requried="true" />
<cfargument name="delimiter1" type="string" required="false" default="&" />
<cfargument name="delimiter2" type="string" required="false" default="=" />
<cfset var buffer = CreateObject("java", "java.lang.StringBuffer").init() />
<cfloop collection="#arguments.struct#" item="key">
<cfset buffer.append(key) />
<cfset buffer.append(delimiter2) />
<cfset buffer.append(arguments.struct[key]) />
<cfset buffer.append(delimiter1) />
</cfloop>
<cfif buffer.length() gt 1>
<cfset buffer.setLength(buffer.length()-1) />
</cfif>
<cfreturn buffer.toString() />
</cffunction>
<cffunction name="ListPairsToStruct" returntype="struct">
<cfargument name="list" type="string" requried="true" />
<cfargument name="delimiter1" type="string" required="false" default="&" />
<cfargument name="delimiter2" type="string" required="false" default="=" />
<cfset var returnValue = StructNew() />
<cfloop list="#arguments.list#" index="pair" delimiters="#arguments.delimiter1#">
<cfset returnValue[ListFirst(pair, arguments.delimiter2)] = ListLast(pair, arguments.delimiter2) />
</cfloop>
<cfreturn returnValue />
</cffunction>