Created
December 14, 2010 05:29
-
-
Save drewbourne/740040 to your computer and use it in GitHub Desktop.
Colorize Flash trace() messages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package asx.string | |
{ | |
public class ColorizeTest | |
{ | |
var colors:Object = { red: red, green: green, yellow: yellow, blue: blue, purple: purple, cyan: cyan, gray: gray }; | |
[Test] | |
public function colorize_shouldReturnColorizedString():void | |
{ | |
for (var color:String in colors) | |
{ | |
var result:String = colors[color](color); | |
trace(result); | |
} | |
} | |
[Test] | |
public function colourize_shouldReturnBoldAndColorizedString():void | |
{ | |
// trace the color name in its color and bold | |
for (var color:String in colors) | |
{ | |
var result:String = colors[color](color + " bold", true); | |
trace(result); | |
} | |
} | |
} | |
} | |
function replaceTokens(formatString:String, data:Object):String | |
{ | |
const TOKEN_PATTERN:RegExp = /{([^\s{}]+)}/g; | |
return formatString.replace(TOKEN_PATTERN, function(... rest):String | |
{ | |
return (data && data.hasOwnProperty(rest[1])) ? data[rest[1]] : rest[0]; | |
}); | |
} | |
function colorize(message:String, color:String = "0"):String | |
{ | |
var format:String = "{escape}[{color}m{message}{escape}[0m"; | |
var replacements:Object = { message: message, color: color, escape: String.fromCharCode(27)}; | |
return replaceTokens(format, replacements); | |
} | |
function red(message:String, bold:Boolean = false):String | |
{ | |
return colorize(message, bold ? "1;31" : "31") | |
} | |
function green(message:String, bold:Boolean = false):String | |
{ | |
return colorize(message, bold ? "1;32" : "32") | |
} | |
function yellow(message:String, bold:Boolean = false):String | |
{ | |
return colorize(message, bold ? "1;33" : "33") | |
} | |
function blue(message:String, bold:Boolean = false):String | |
{ | |
return colorize(message, bold ? "1;34" : "34") | |
} | |
function purple(message:String, bold:Boolean = false):String | |
{ | |
return colorize(message, bold ? "1;35" : "35") | |
} | |
function cyan(message:String, bold:Boolean = false):String | |
{ | |
return colorize(message, bold ? "1;36" : "36") | |
} | |
function gray(message:String, bold:Boolean = false):String | |
{ | |
return colorize(message, bold ? "1;37" : "37") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A good refactor would be:
function colorize(message:String, color:String = "0", showBold:Boolean=false):String {
color = showBold ? "1;"+color : color;
}