Wednesday, October 29, 2008

Variable converter from camelCase to under_score

I had to write this for work and then we ended up taking care of the code a different way. Didn't want to lose it. This util converts Strings (variable names) from camelCase to under_score, since the underscore way was how the php backend preferred it. I know the formatting is messed up; just copy and paste it; it has to do with the sizes of the tabs. Enjoy!

package utils
{
/**
* This class for converting variables from camelCase to underscore_vars or vice versa.
*/
public class VariableConverter
{
//-----------------------------------------------------------------------------------------
//
// Variables
//
//-----------------------------------------------------------------------------------------

/**
* The character codes for the letters 'A' and 'Z'.
*/
protected static const A:uint = 65;
protected static const Z:uint = 90;

/**
* If 'camelToUnder' == true, convert the variable name from camelCase to under_score
* format, else vice versa.
*/
public static function convert(value:String, camelToUnder:Boolean = true):String
{
// The var 'camelToUnder', when true, specifies that this function
//-- treat incoming vars as camelCase for converting to underscore format. If set to
//-- false, incoming vars are converted from underscore format to camelCase.

for (var i:uint = 0; i < value.length; i++)
{
// Find the index of each significant character: a capital letter if
//-- 'camelToUnder' == true, and an underscore if false. Splice what happened
//-- before the character to the altered or deleted character and what
//-- should come after it.

var str:String = value.charAt(i);
if (camelToUnder && str.charCodeAt(0) >= A && str.charCodeAt(0) <= Z)
{
var beginning:String = value.substring(0, i);
var ending:String = value.substring(i + 1, value.length);
value = beginning + '_' + str.toLowerCase() + ending;

// Add to 'i' because the String is longer, now.
i++;
}
else if (!camelToUnder && str == '_')
{
beginning = value.substr(0, i);
ending = value.substr(i + 2, value.length);
value = beginning + value.charAt(i + 1).toUpperCase() + ending;

// Subtract from 'i' because the string is shorter, now.
i--;
}
}

return value;
}

} // End class
}