The Cure for CFIF/CFELSEIF Hell – Revisited

Posted: December 6, 2007 in ColdFusion

Hello World,

I must give props to Jeff Price for suggesting a way to improve the code I published in my previous post. Here is the improved function:

<cffunction name="arrayValsToBitFlags" access="private" output="false" returntype="numeric">
	<cfargument name="myArray" type="array" required="yes"> 

	<cfset total = 0>

	<!--- loop over array --->
	<cfloop from="1" to="#ArrayLen(myArray)#" index="myIndex">

		<!--- if the the array item has a length or use your own criteria --->
		<cfif Len(myArray&#91;myIndex&#93;)>

			<!--- use powers of two to set the appropriate bit and add to the rest. Remember CF arrays start at 1 so subtract that! --->
			<cfset total += 2^(myIndex-1)>

	<cfreturn total>

And here is an example how you would use it:

<cfset myArgs = &#91;"1","","Hello","World",""&#93;>
<cfset total = arrayValsToBitFlags(myArgs)>

As you can see his version is much improved as it doesn’t require you to pass into the function a number value. Also, passing in an array makes the function call shorter and easier to read. Thanks Jeff!Ciao

  1. Ben Nadel says:

    I like the use of bit masking… I don’t use Bits all that much, but I love the concept. Also, don’t forget to “var” your Total variable 🙂

  2. extrapreneur says:

    Ha, that makes life easier.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s