Can you execute optional parameters in a function via cfscript?

I'm finally going to write stuff in cfscript, and so I'm starting to write some necessary formatting functions. Here is an example:

Function FormatBoolean(MyBool, Format) { Switch(Format){ Case "YES/NO":{ If (MyBool eq 1) Return "YES"; Else Return "NO"; Break; } Default:{ If (MyBool eq 1) Return "Yes"; Else Return ""; Break; } } } 

What I would like to do is make Format an optional argument. If you do not include this argument, the function will still work, but it will not find the format, and it seems that cfparam is not being translated into cfscript.

I just have to check if the format is defined and assign a value to it? Or is there a better way to do this?

thanks

+8
coldfusion coldfusion-9
source share
2 answers

Personally, I prefer to set default values ​​for such arguments. I also edited the function a bit ... But not tested :)

 function FormatBoolean(required any MyBool, string Format = "") { switch(arguments.Format) { case "YES/NO": return YesNoFormat(arguments.MyBool EQ 1); default: return (arguments.MyBool eq 1) ? "Yes" : ""; } } 

Note that (arguments.MyBool EQ 1) can be replaced with (arguments.MyBool) , so it covers all boolean values. You may be interested in making it more reliable, something like this (isValid("boolean", arguments.MyBool) AND arguments.MyBool) - this should allow any value to be checked at all.

+13
source share

All variables passed to the function are accessible programmatically through the ARGUMENTS area. You can refer to it as if it were an array (because it is), as well as standard access to the key structure (which I did for you below for the MyBool parameter):

 <cfscript> Function FormatBoolean(MyBool) { var theFormat = ''; if (ArrayLen(ARGUMENTS) GT 1) theFormat = ARGUMENTS[2]; Switch(theFormat){ Case "YES/NO":{ If (ARGUMENTS.MyBool eq 1) Return "YES"; Else Return "NO"; Break; } Default:{ If (ARGUMENTS.MyBool eq 1) Return "Yes"; Else Return ""; Break; } } } </cfscript> 

If necessary, add preferred additional levels of data verification.

+1
source share

All Articles