views:

262

answers:

4

Inside my function there is an if() statement like this:

if(passedValue < staticValue)

But I need to be able to pass a parameter dictating whether the if expression is like above or is:

if(passedValue > staticValue)

But I cant really pass < or > operator in has a parameter, so I was wondering what is the best way to do this?

Also if the language I am using matters its ActionScript 3.0

Thanks!!

A: 

I don't know Actionscript, but can't you make a variable called:

bool greaterThan = true;

and if its true, do >, if its false do < ?

Jack Marchetti
+1  A: 

Why not make the function take a bool as an argument and perform the comparison directly when calling the function?

ExampleFunction(arg1, (passedValue > staticValue))
Mike
What if the callee has no access to staticValue?
LiraNuna
A: 

You're right, you can't pass operators. You can pass a variable indicating which operator to use though.

lessThan = true;
func(passedValue, lessThan); 
Seth
+5  A: 

Instead of passing an operator, which is impossible in AS3, why not pass a custom comparison function?

function actualFunction(passedValue:Number, compareFunction:Function) {
    /* ... */

    if(compareFunction(passedValue, staticValue)) {
        /* ... Do something ... */
    }

    /* ... */
}

Then to use it:

actualFunction(6, function(x:Number, y:Number) {
     return x > y;
});

or:

actualFunction(6, function(x:Number, y:Number) {
     return x < y;
});
LiraNuna
Good solution. Alternatively, if the author wanted to pass the operator as a string, they could use it as a lookup to retrieve the correct function (from a dictionary, or similar). It would require more setup, optionally simplified with a factory, but would result in cleaner code. (ie: not creating a dynamic function each place the call is made)
Tyler Egeto
Tyler: I don't think it's "cleaner" - it's way more code to maintain...
LiraNuna
"(ie: not creating a dynamic function each place the call is made)" - Flash optimizes the function to be static, so there's no performance penalty.
LiraNuna