Ask a Jedi: Dynamic math?

Jim asks:

Ray, I'm just playing and can't figure this out.

Given:
<cffunction name="makeRandomNum" returntype="numeric" output="false">
<cfset var result = RandRange(0,10)>
<cfreturn result>
</cffunction>
<cfset num1 = makeRandomNum()>
<cfset num2 = makeRandomNum()>
<cfset Oper = mid("+-*", randRange(1,3),1)>

<cfset ans = num1 Oper num2>

How can I get var Oper reconized as mathical operator?

This is one of the few times where the evaluate function is necessary. In order to get ans to represent the right value, we can easily switch it to:

<cfset ans = evaluate("num1 #oper# num2")>

Of course, this isn't the only way. Since the number of mathematical operands are limited, you could always write a UDF that takes all 3 values (the two numeric value and the operand) and simply uses a switch case to determine which one to run. But that would be overkill and a complete waste of time, so only an idiot would do it.

<cffunction name="makeRandomNum" returntype="numeric" output="false"> <cfset var result = RandRange(0,10)> <cfreturn result> </cffunction> <cfset num1 = makeRandomNum()> <cfset num2 = makeRandomNum()> <cfset Oper = mid("+-*", randRange(1,3),1)> <cfoutput>oper=#oper# num1=#num1# num2=#num2#, #evaluate("num1 #oper# num2")#<br></cfoutput> <cfscript> function wasteOfTime(num1,num2,oper) { switch(oper) { case "+": return num1+num2; case "-": return num1-num2; case "*": return num1*num2; case "/": return num1/num2; } return "NAN"; } </cfscript> <p> <cfoutput>#wasteOfTime(num1,num2,oper)#</cfoutput> Enjoy.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments