Posts / renderTable#15

Render table

By Toby Hinloopen at 2021-03-19 16:37

Installation

# npm
npm i https://boomm.io/p/15-render-table.tar.gz
# yarn
yarn add https://boomm.io/p/15-render-table.tar.gz

Usage

const renderTable = require("15-render-table");

Source

"use strict";
// requires lodash
// requires chalk
// yarn add lodash chalk
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var lodash_1 = __importDefault(require("lodash"));
var chalk_1 = __importDefault(require("chalk"));
function renderTable(rows) {
    var columnCount = lodash_1.default(rows).map("cells").map("length").max();
    var columnWidths = lodash_1.default(columnCount).times().map(function (colIndex) { return getColumnWidth(rows, colIndex); });
    var lines = lodash_1.default(rows).map(function (row) { return renderLine(row, columnWidths); });
    return lines.join("\n");
}
exports.default = renderTable;
function renderLine(row, columnWidths) {
    var style = toArray(row.style || []).reduce(function (acc, key) { return acc[key]; }, chalk_1.default);
    var cells = row.cells;
    return style(columnWidths.map(function (width, index) { return renderCellBody(cells[index] || "", width); }).join(" | "));
}
function getColumnWidth(rows, colIndex) {
    return lodash_1.default(rows).map("cells").map(colIndex).compact().map(cellWidth).max();
}
function cellWidth(cell) {
    return typeof cell === "string" ? cell.length : cell.join("").length;
}
function toArray(val) {
    return val instanceof Array ? val : [val];
}
function renderCellBody(cell, width) {
    if (typeof cell === "string") {
        return lodash_1.default.padEnd(cell, width, " ");
    }
    else {
        var left = cell[0], right = cell[1];
        return left + lodash_1.default.padStart(right, width - left.length, " ");
    }
}