Skip to content
Browse files

Merge branch 'util_format' of git://github.com/exfm/node-browserify i…

…nto exfm-util_format
  • Loading branch information...
2 parents 10a1dfb + a532e03 commit 5f9a59aa527504544846eea5b6a71df17c6add3c @substack committed Sep 20, 2012
Showing with 34 additions and 0 deletions.
  1. +34 −0 builtins/util.js
View
34 builtins/util.js
@@ -310,3 +310,37 @@ exports.inherits = function(ctor, superCtor) {
}
});
};
+
+var formatRegExp = /%[sdj%]/g;
+exports.format = function(f) {
+ if (typeof f !== 'string') {
+ var objects = [];
+ for (var i = 0; i < arguments.length; i++) {
+ objects.push(exports.inspect(arguments[i]));
+ }
+ return objects.join(' ');
+ }
+
+ var i = 1;
+ var args = arguments;
+ var len = args.length;
+ var str = String(f).replace(formatRegExp, function(x) {
+ if (x === '%%') return '%';
+ if (i >= len) return x;
+ switch (x) {
+ case '%s': return String(args[i++]);
+ case '%d': return Number(args[i++]);
+ case '%j': return JSON.stringify(args[i++]);
+ default:
+ return x;
+ }
+ });
+ for(var x = args[i]; i < len; x = args[++i]){
+ if (x === null || typeof x !== 'object') {
+ str += ' ' + x;
+ } else {
+ str += ' ' + exports.inspect(x);
+ }
+ }
+ return str;
+};

0 comments on commit 5f9a59a

Please sign in to comment.
Something went wrong with that request. Please try again.