Testing if an object is in a set
One useful operator I've found when writing MySQL queries is the "IN" operator. The elegance of the simple statement to see if a value is equal to any item in a set is something I've alway wanted to have at my fingertip while writing much of the code I do in AS3. At some point I got tired of using something akin to as3corelib's ArrayUtils.arrayContainsValue function as I wanted to see if I could find a better solution for more readable code.
AS3's "in" operator
My first stop was AS3's "in" operator. At first it seemed like it might work and the code would look like the following:
value in [apple,banana,kiwi,orange]
Unfortunately, the previous line would only resolve to true if value was equal to 0,1,2 or 3. The in
operator only checks against the indexes of an array ( or the fields in an object ). So unfortunately it wouldn't work for my needs. It looks like I was going to have to roll my own and I wanted to see if I could create something that read like the following:
anyObject.isIn( ... args )
Actionscript is [still] a prototype language
Back in the days of AS1 and AS2 you could easily add functionality by adding to a class's prototype chain. If you wanted to add functionality to everything, all you would have to do is add to the Object
class prototype. The good news, is that this is still possible in AS3. The [not quite] bad news is that due to strong type checking you can't have a line like I wrote above without disabling strict type checking in the compiler. That's not something I'm willing to give up so I came up with something that could look like the line above but with strict type checking enabled it would look like the following:
anyObject[IS_IN]( ... args )
A little less readable than I would like but using the IS_IN
constant has a benefit of making it easy to import and use with Flex/Flash Builder. It also has the benefit of working with anything that extends objects which has some cool benefits. For instance you can write the following:
4[IS_IN]( 1, 2, 3, 4 ); // returns true
true[IS_IN]( true ); // returns true
true[IS_IN]( 1 ); // returns false
"foo"[IS_IN]( "foo", "bar" ); // returns true
If this sounds like something you might like to use feel free to download the file. I've also included my flexUnit4 test class which will show you more of how this can be used.
EDIT: There are some problems with this file as it was originally created as a proof of concept. For educational purposes I am keeping the original file up here and you can learn about the changes and why I made them at: http://ducharme.cc/flash-friday-is-in-refactored/