@tduyng/prettyoutput
Version:
Library to format JSON objects into a colorful, YAML-style output. Ideal for pretty printing logs with high performance.
78 lines • 2.39 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSerializable = exports.repeat = exports.colorString = exports.alignString = exports.maxLength = exports.indent = void 0;
const colors_js_1 = require("./colors.js");
const cache = new Map();
const CLEANUP_THRESHOLD = 1000;
let cacheInsertCount = 0;
const cleanupCache = () => {
cache.clear();
};
/**
* Creates a string with specified spaces count
* @param {number} spaceCount - space count
* @return {string}
*/
const indent = (spaceCount) => {
if (!cache.has(spaceCount)) {
cache.set(spaceCount, ' '.repeat(spaceCount));
cacheInsertCount++;
if (cacheInsertCount >= CLEANUP_THRESHOLD) {
cacheInsertCount = 0;
cleanupCache();
}
}
return cache.get(spaceCount);
};
exports.indent = indent;
/**
* Gets longest string length
* @param {Array<string>} strings
* @return {number}
*/
const maxLength = (strings) => {
let max = 0;
for (const str of strings) {
if (str?.length > max)
max = str.length;
}
return max;
};
exports.maxLength = maxLength;
/**
*
* @param {string} input - single or multiline string
* @param {string} indentation - indentation space as string
* @return {string} - Indented multiline string
*/
const alignString = (input, indentation) => input
.split('\n')
.map((line) => `${indentation}${line}`)
.join('\n');
exports.alignString = alignString;
/**
*
* @param {string} input
* @param {string} color name
* @return {string} - colored string (for terminal output)
*/
const colorString = (input, color) => color ? `${colors_js_1.colors[color](input)}` : input;
exports.colorString = colorString;
const repeat = (string, count) => string.repeat(Math.max(0, count));
exports.repeat = repeat;
/**
* Serializable values are boolean, number, null, Date, Single line strings, empty arrays
* @param {*} input
* @return {boolean}
*/
const isSerializable = (input) => {
if (input === null || input === undefined)
return true;
if (typeof input === 'boolean' || typeof input === 'number' || input instanceof Date)
return true;
if (typeof input === 'string' && !input.includes('\n'))
return true;
return Array.isArray(input) && input.length === 0;
};
exports.isSerializable = isSerializable;
//# sourceMappingURL=utils.js.map