-
Notifications
You must be signed in to change notification settings - Fork 6
/
format.js
42 lines (38 loc) · 890 Bytes
/
format.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function format(fmt) {
var re = /(%?)(%([ojds]))/g
, args = Array.prototype.slice.call(arguments, 1);
if(args.length) {
fmt = fmt.replace(re, function(match, escaped, ptn, flag) {
var arg = args.shift();
switch(flag) {
case 'o':
if (Array.isArray(arg)) {
arg = JSON.stringify(arg);
break;
}
case 's':
arg = '' + arg;
break;
case 'd':
arg = Number(arg);
break;
case 'j':
arg = JSON.stringify(arg);
break;
}
if(!escaped) {
return arg;
}
args.unshift(arg);
return match;
})
}
// arguments remain after formatting
if(args.length) {
fmt += ' ' + args.join(' ');
}
// update escaped %% values
fmt = fmt.replace(/%{2,2}/g, '%');
return '' + fmt;
}
module.exports = format;