UNPKG

better-consoley

Version:

Better-consoley It is a drop-in replacement for Node's default console that provides additional colors in console

62 lines (61 loc) 2.31 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.logTable = logTable; const cli_table3_1 = __importDefault(require("cli-table3")); const chalk_1 = __importDefault(require("chalk")); const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null; const defaultHeaderColor = chalk_1.default.cyan; function logTable(data) { if (!Array.isArray(data) || data.length === 0 || typeof data[0] !== 'object') { console.error(chalk_1.default.red('Invalid data format. Please provide an array of objects.')); return; } if (isNode) { renderNodeTable(data); } else { renderBrowserTable(data); } } function renderNodeTable(data) { const headers = Object.keys(data[0]); headers.unshift('(index)'); const colWidths = headers.map((_, i) => calculateColWidth(data, i)); const table = new cli_table3_1.default({ head: headers.map(header => defaultHeaderColor(header)), colWidths: colWidths, }); data.forEach((row, rowIndex) => { const rowValues = headers.slice(1).map(key => (key in row ? stringifyCell(row[key]) : '')); table.push([rowIndex.toString(), ...rowValues]); }); console.log(table.toString()); } function renderBrowserTable(data) { const formattedData = data.map((row, index) => { return Object.assign({ "(index)": index }, row); }); console.table(formattedData); } function calculateColWidth(data, columnIndex) { const MAX_COL_WIDTH = 28; const MIN_COL_WIDTH = 3; const columnValues = data.map((row, rowIndex) => { if (columnIndex === 0) return rowIndex.toString(); const key = Object.keys(data[0])[columnIndex - 1]; return key in row ? stringifyCell(row[key]) : ''; }); const maxWidth = Math.max(...columnValues.map(val => val.length), MIN_COL_WIDTH); return Math.min(maxWidth, MAX_COL_WIDTH) + 2; } function stringifyCell(value) { if (value === null || value === undefined) return ''; if (typeof value === 'object') return JSON.stringify(value); return value.toString(); }