Skip to content

Commit

Permalink
fix multi-arg and format handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Qix- committed Aug 13, 2017
1 parent 58ceaa0 commit e179414
Showing 1 changed file with 39 additions and 19 deletions.
58 changes: 39 additions & 19 deletions src/debug.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,15 @@ exports.skips = [];
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/

exports.formatters = {};
exports.formatters = {
s: String,
i: function (v) {
v = Number(v);
return v - (v % 1);
},
d: Number,
f: Number
};

/**
* Select a color.
Expand All @@ -50,6 +58,32 @@ function selectColor(namespace) {
return exports.colors[Math.abs(hash) % exports.colors.length];
}

/**
* Formats a sequence of arguments.
* @api private
*/

function formatInlineArgs(dbg, args) {
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(dbg, val);

// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});

return args;
}

/**
* Create a debugger with the given `namespace`.
*
Expand Down Expand Up @@ -90,22 +124,7 @@ function createDebug(namespace) {
}

// apply any `formatters` transformations
var index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
// if we encounter an escaped % then don't increase the array index
if (match === '%%') return match;
index++;
var formatter = exports.formatters[format];
if ('function' === typeof formatter) {
var val = args[index];
match = formatter.call(self, val);

// now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
formatInlineArgs(self, args);

// apply env-specific formatting (colors, etc.)
exports.formatArgs.call(self, args, section);
Expand Down Expand Up @@ -140,8 +159,9 @@ function createDebug(namespace) {
section.title = title;
section.deltaTime = exports.hrtime(beginTime);
if (extraArgs.length) {
var newArgParams = [].slice.call(args, 1).concat([].slice.call(extraArgs, 1))
var newArgs = [(args[0] ? args[0] + ' :: ' : '') + (extraArgs[0] || '')].concat(newArgParams);
var leftArgs = formatInlineArgs(debug, [].slice.call(args));
var rightArgs = formatInlineArgs(debug, [].slice.call(extraArgs));
var newArgs = (leftArgs.length > 0 && rightArgs.length > 0) ? leftArgs.concat(['::']).concat(rightArgs) : leftArgs.concat(rightArgs);
debugHandle(newArgs, section);
} else {
debugHandle(args, section);
Expand Down

0 comments on commit e179414

Please sign in to comment.