util-ex
Version:
Browser-friendly enhanced util fully compatible with standard node.js
79 lines (78 loc) • 2.44 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.format = format;
var _object = _interopRequireDefault(require("./is/type/object.js"));
var _null = _interopRequireDefault(require("./is/type/null.js"));
var _string = _interopRequireDefault(require("./is/type/string.js"));
var _inspect = _interopRequireDefault(require("./inspect.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const formatRegExp = /%[sdj%]/g;
/**
* Formats a string using placeholder tokens.
*
* If the first argument is a string, it is treated as a format string that
* specifies placeholders for the subsequent arguments, which will be inserted
* into the string in place of the placeholders. The placeholders are
* specified using '%s' for string, '%d' for number, and '%j' for JSON.
*
* If the first argument is not a string, all arguments will be inspected and
* concatenated into a space-separated string.
*
* @param {string|any} f - The format string or object to be formatted.
* @param {...any} args - The values to be inserted into the format string.
* @returns {string} The formatted string.
*
* @example
* format('%s %s', 'hello', 'world'); // 'hello world'
* format('%d %s', 42, 'answer'); // '42 answer'
* format('%j', { foo: 'bar' }); // '{'foo':'bar'}'
* format('no placeholders', 'needed'); // 'no placeholders needed'
*/
function format(f) {
let i;
if (!(0, _string.default)(f)) {
const objects = [];
for (i = 0; i < arguments.length; i++) {
objects.push((0, _inspect.default)(arguments[i]));
}
return objects.join(' ');
}
i = 1;
const args = arguments;
const len = args.length;
let str = String(f).replace(formatRegExp, x => {
if (x === '%%') {
return '%.js';
}
if (i >= len) {
return x;
}
switch (x) {
case '%s':
return String(args[i++]);
case '%d':
return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular].js';
}
default:
return x;
}
});
for (let x = args[i]; i < len; x = args[++i]) {
if ((0, _null.default)(x) || !(0, _object.default)(x)) {
str += ` ${x}`;
} else {
str += ` ${(0, _inspect.default)(x)}`;
}
}
return str;
}
;
var _default = exports.default = format;