You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
2.4 KiB

'use strict'
function tryStringify (o) {
try { return JSON.stringify(o) } catch(e) { return '"[Circular]"' }
}
module.exports = format
function format(f, args, opts) {
var ss = (opts && opts.stringify) || tryStringify
var offset = 1
if (f === null) {
f = args[0]
offset = 0
}
if (typeof f === 'object' && f !== null) {
var len = args.length + offset
if (len === 1) return f
var objects = new Array(len)
objects[0] = ss(f)
for (var index = 1; index < len; index++) {
objects[index] = ss(args[index])
}
return objects.join(' ')
}
var argLen = args.length
if (argLen === 0) return f
var x = ''
var str = ''
var a = 1 - offset
var lastPos = 0
var flen = (f && f.length) || 0
for (var i = 0; i < flen;) {
if (f.charCodeAt(i) === 37 && i + 1 < flen) {
switch (f.charCodeAt(i + 1)) {
case 100: // 'd'
if (a >= argLen)
break
if (lastPos < i)
str += f.slice(lastPos, i)
if (args[a] == null) break
str += Number(args[a])
lastPos = i = i + 2
break
case 79: // 'O'
case 111: // 'o'
case 106: // 'j'
if (a >= argLen)
break
if (lastPos < i)
str += f.slice(lastPos, i)
if (args[a] === undefined) break
var type = typeof args[a]
if (type === 'string') {
str += '\'' + args[a] + '\''
lastPos = i + 2
i++
break
}
if (type === 'function') {
str += args[a].name || '<anonymous>'
lastPos = i + 2
i++
break
}
str += ss(args[a])
lastPos = i + 2
i++
break
case 115: // 's'
if (a >= argLen)
break
if (lastPos < i)
str += f.slice(lastPos, i)
str += String(args[a])
lastPos = i + 2
i++
break
case 37: // '%'
if (lastPos < i)
str += f.slice(lastPos, i)
str += '%'
lastPos = i + 2
i++
break
}
++a
}
++i
}
if (lastPos === 0)
str = f
else if (lastPos < flen) {
str += f.slice(lastPos)
}
while (a < argLen) {
x = args[a++]
if (x === null || (typeof x !== 'object')) {
str += ' ' + String(x)
} else {
str += ' ' + ss(x)
}
}
return str
}