Add printf format compatibility

This commit is contained in:
Guillaume Wuip 2014-10-26 14:34:59 +01:00
parent 2c53de8ee6
commit e11d2e1bd9
2 changed files with 58 additions and 25 deletions

View file

@ -25,3 +25,5 @@ console.log(
); );
console.tag("Combo!").time().file().log("A combo"); console.tag("Combo!").time().file().log("A combo");
console.log("A string %s and a number %d", "hello", "123"); //you can you printf-like format

View file

@ -74,6 +74,26 @@
return '[' + infos.filename + ':' + infos.line + ']'; return '[' + infos.filename + ':' + infos.line + ']';
}; };
/**
* areAllStringOrNumber
*
* Check in an array contains only string and number
*
* @param {Array} arr
* @retrun {Boolean}
*/
var areAllStringOrNumber = function (arr) {
arr.forEach(function (elem) {
if (typeof elem !== 'string' && typeof elem !== 'number') {
return false;
}
});
return true;
};
/** /**
* applyColors * applyColors
* *
@ -194,7 +214,7 @@
this._tags = []; this._tags = [];
this._time = false; this._time = false;
this._date = false; this._date = false;
this.location = false; this._location = false;
return this; return this;
}; };
@ -234,7 +254,9 @@
* Console2.prototype.tag * Console2.prototype.tag
* *
* Add tags * Add tags
* @param {*} tag * @param {String|Object} tag
* @param {String} tag.msg The tag
* @paral {String|Array} tag.color colors.js colors
*/ */
Console2.prototype.tag = Console2.prototype.t = function () { Console2.prototype.tag = Console2.prototype.t = function () {
var tags = Array.prototype.slice.call(arguments, 0); var tags = Array.prototype.slice.call(arguments, 0);
@ -311,8 +333,16 @@
//It's time to log the args //It's time to log the args
var args = Array.prototype.slice.call(log.args, 0), //transform args in an array var args = Array.prototype.slice.call(log.args, 0), //transform args in an array
msg = "", //the log message msg = ""; //the log message
delimiter = '\n\n',
//if all args are string or number, format args as usual
if (areAllStringOrNumber(args)) {
msg = util.format.apply(this, args);
//if objects or array present
} else {
var delimiter = '\n\n',
multiLines = false; //if the log need multiples lines (ie. object, array) multiLines = false; //if the log need multiples lines (ie. object, array)
//Process arg one by one //Process arg one by one
@ -341,6 +371,7 @@
msg += '\n'; msg += '\n';
msg = msg.replace(/\n/gm, '\n' + new Array(this.opt.spaceSize).join(' ')); msg = msg.replace(/\n/gm, '\n' + new Array(this.opt.spaceSize).join(' '));
} }
}
result += msg; result += msg;