1, true, yes, y, on? - A Boolean Converter in AS3

Configuration files often contain Boolean parameters for enabling or disabling features in an application or website. This way non-programmers can easily customize complex systems. But what if someone uses another word than “true” (for example, “1″, “yes”, “y”, “on”)?

In order to make my Flash/Flex apps less error-prone, I usually run all Boolean values from external configuration files through a converter. It’s a simple class with a single static method:

  1. package
  2. {
  3.    public class BooleanConverter
  4.    {
  5.  
  6.       public static const TRUE_VALUES:Array = [ "1", "true", "yes", "y", "on", "enabled" ];
  7.    
  8.       public static function makeBoolean( val:* ):Boolean
  9.       {
  10.          var str:String = String( val ).toLowerCase();
  11.    
  12.          for ( var i:int = 0; i < BooleanConverter.TRUE_VALUES.length; i++ )
  13.          {
  14.             if ( str == BooleanConverter.TRUE_VALUES[i] )
  15.             {
  16.                return true;
  17.             }
  18.          }
  19.          return false;  
  20.       }
  21.  
  22.    }
  23. }

The method makeBoolean() accepts any type of data and converts it into a string. The string value is then compared to a list of words which represent the Boolean status true. If no match is found false is returned.

Tags: , ,

2 Responses to “1, true, yes, y, on? - A Boolean Converter in AS3”

  1. Psychic Advice Says:

    Great blog, subscribed to your rss feed. Thanks.

  2. Import from China Says:

    Great info - keep up the great work.

Leave a Reply