diff --git a/colors.js b/colors.js index cfe3a35..9dcfc44 100644 --- a/colors.js +++ b/colors.js @@ -24,13 +24,21 @@ THE SOFTWARE. */ // prototypes the string object to have additional method calls that add terminal colors + +var addProperty = function (color, func) { + exports[color] = function(str) { + return func.apply(str); + }; + String.prototype.__defineGetter__(color, func); +} + var isHeadless = (typeof module !== 'undefined'); ['bold', 'underline', 'italic', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'].forEach(function (style) { // __defineGetter__ at the least works in more browsers // http://robertnyman.com/javascript/javascript-getters-setters.html // Object.defineProperty only works in Chrome - String.prototype.__defineGetter__(style, function () { + addProperty(style, function () { return isHeadless ? stylize(this, style) : // for those running in node (headless environments) this.replace(/( )/, '$1'); // and for those running in browsers: @@ -40,7 +48,7 @@ var isHeadless = (typeof module !== 'undefined'); // prototypes string with method "rainbow" // rainbow will apply a the color spectrum to a string, changing colors every letter -String.prototype.__defineGetter__('rainbow', function () { +addProperty('rainbow', function () { if (!isHeadless) { return this.replace(/( )/, '$1'); } @@ -82,7 +90,7 @@ function stylize(str, style) { }; // don't summon zalgo -String.prototype.__defineGetter__('zalgo', function () { +addProperty('zalgo', function () { return zalgo(this); }); diff --git a/example.js b/example.js index 13b9fae..3003581 100644 --- a/example.js +++ b/example.js @@ -4,4 +4,10 @@ var colors = require('./colors'); sys.puts('Rainbows are fun!'.rainbow); sys.puts('So '.italic + 'are'.underline + ' styles! '.bold + 'inverse'.inverse); // styles not widely supported sys.puts('Chains are also cool.'.bold.italic.underline.red); // styles not widely supported -// sys.puts('zalgo time!'.zalgo); \ No newline at end of file +//sys.puts('zalgo time!'.zalgo); + + +sys.puts(colors.rainbow('Rainbows are fun!')); +sys.puts(colors.italic('So ') + colors.underline('are') + colors.bold(' styles! ') + colors.inverse('inverse')); // styles not widely supported +sys.puts(colors.bold(colors.italic(colors.underline(colors.red('Chains are also cool.'))))); // styles not widely supported +//sys.puts(colors.zalgo('zalgo time!'));