### Install voici.js via npm Source: https://github.com/larswaechter/voici.js/blob/main/README.md This command installs the voici.js library as a dependency for your Node.js project using npm. It is essential before using the library in your application. ```bash npm i --save voici.js ``` -------------------------------- ### Create Styled Table with Alignment and Borders in Node.js Source: https://context7.com/larswaechter/voici.js/llms.txt Shows how to configure table appearance using custom alignment, borders, padding, and column colors in voici.js. This example highlights extensive styling options for professional terminal output. ```javascript import { Table } from 'voici.js'; const data = [ { id: 1, product: 'Laptop', price: 999.99, stock: 15 }, { id: 2, product: 'Mouse', price: 29.99, stock: 150 }, { id: 3, product: 'Keyboard', price: 79.99, stock: 45 } ]; const table = new Table(data, { align: 'CENTER', border: { horizontal: '-', vertical: '|', color: '#888888', groupSize: 2 }, padding: { char: ' ', size: 3 }, bgColorColumns: ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A'], header: { bold: true, uppercase: true, bgColor: '#2C3E50', textColor: '#ECF0F1', separator: '=' }, body: { striped: true, bgColor: '#34495E', textColor: '#FFFFFF' } }); table.print(); ``` -------------------------------- ### GET /config Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Retrieves the current configuration for the table. This endpoint allows you to get the full configuration object, which includes settings for alignment, background colors, body styling, borders, headers, and sorting. ```APIDOC ## GET /config ### Description Retrieves the current configuration for the table. This endpoint allows you to get the full configuration object, which includes settings for alignment, background colors, body styling, borders, headers, and sorting. ### Method GET ### Endpoint /config ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **align** (string) - Specifies the text alignment for the table. Can be 'LEFT', 'CENTER', or 'RIGHT'. - **bgColorColumns** (string[]) - An array of strings representing background colors for specific columns. - **body** (object) - Configuration for the table body. - **accumulation** (object) - Configuration for accumulation display in the body. - **bgColor** (string) - Background color for accumulation cells. - **columns** (object) - Configuration for accumulation columns. - **separator** (string) - Separator string for accumulation values. - **bgColor** (string) - Background color for the table body. - **fillEmpty** (object) - Configuration for filling empty cells. - **filterRow** (function) - A function to filter rows based on row data and index. - **highlightCell** (object) - Configuration for highlighting individual cells. - **bold** (boolean) - Whether to render cell content in bold. - **func** (function) - A function to determine if a cell should be highlighted. - **italic** (boolean) - Whether to render cell content in italics. - **textColor** (string) - Text color for highlighted cells. - **underline** (boolean) - Whether to underline cell content. - **highlightRow** (object) - Configuration for highlighting entire rows. - **bgColor** (string) - Background color for highlighted rows. - **func** (function) - A function to determine if a row should be highlighted. - **peek** (number | [number, number]) - Specifies a peek value or range for rows. - **precision** (number) - Number of decimal places for numerical data. - **striped** (boolean) - Whether to apply a striped background to rows. - **subset** (Array) - Defines a subset of rows to display. - **textColor** (string) - Default text color for the table body. - **border** (object) - Configuration for table borders. - **color** (string) - Color of the table borders. - **groupSize** (number) - Size of border groups. - **horizontal** (string) - Style for horizontal borders. - **vertical** (string) - Style for vertical borders. - **header** (object) - Configuration for the table header. - **bgColor** (string) - Background color for the header. - **bold** (boolean) - Whether to render header text in bold. - **displayNames** (object) - Custom display names for header columns. - **dynamic** (object) - Configuration for dynamic columns in the header. - **exclude** (Array) - List of attributes to exclude from the header. - **include** (Array) - List of attributes to include in the header. - **italic** (boolean) - Whether to render header text in italics. - **lowercase** (boolean) - Whether to render header text in lowercase. - **maxWidth** (number | "auto") - Maximum width for header cells. - **order** (Array) - Specifies the order of header columns. - **origin** (boolean) - Whether to include origin columns in the header. - **separator** (string) - Separator string for header values. - **textColor** (string) - Text color for the header. - **underline** (boolean) - Whether to underline header text. - **uppercase** (boolean) - Whether to render header text in uppercase. - **upperfirst** (boolean) - Whether to render the first letter of header text as uppercase. - **visible** (boolean) - Whether the header is visible. - **width** (number | "auto" | "stretch") - Width of header cells. - **padding** (object) - Configuration for cell padding. - **char** (string) - Character used for padding. - **size** (number) - Size of the padding. - **sort** (object) - Configuration for table sorting. #### Response Example ```json { "align": "LEFT", "bgColorColumns": ["#f0f0f0"], "body": { "accumulation": { "bgColor": "#e0e0e0", "separator": ", " }, "bgColor": "#ffffff", "fillEmpty": {}, "highlightCell": { "bold": false, "italic": false, "textColor": "#000000", "underline": false }, "highlightRow": { "bgColor": "#d0d0d0" }, "peek": 10, "precision": 2, "striped": true, "subset": [0, 100], "textColor": "#333333" }, "border": { "color": "#cccccc", "groupSize": 1, "horizontal": "solid", "vertical": "solid" }, "header": { "bgColor": "#f5f5f5", "bold": true, "displayNames": {}, "exclude": [], "include": [], "italic": false, "lowercase": false, "maxWidth": "auto", "order": [], "origin": false, "separator": " ", "textColor": "#111111", "underline": false, "uppercase": false, "upperfirst": false, "visible": true, "width": "auto" }, "padding": { "char": " ", "size": 2 }, "sort": {} } ``` ``` -------------------------------- ### Array Data with Column Customization (JavaScript) Source: https://context7.com/larswaechter/voici.js/llms.txt This example illustrates how to render data provided as arrays, where columns are accessed by numeric indices. It demonstrates reordering columns, setting custom display names, and defining dynamic columns using the `header` configuration. Requires `voici.js`. ```javascript import { Table } from 'voici.js'; interface DynamicCols { id2: number; } type UserData = [number, string, string, string, string, Date]; const arrayData: UserData[] = [ [1, 'John', 'Doe', 'johndoe@gmail.com', 'Male', new Date(1997, 7, 28)], [45, 'Hermine', 'Granger', 'hermine@gryffindor.com', 'Female', new Date(1991, 5, 12)], [421, 'Max', 'Mustermann', 'mamu@stermann.com', 'Male', new Date(2004, 10, 15)], [2003, 'Peter', 'Parker', 'spiderman@dummynet.com', 'Male', new Date(1980, 1, 4)] ]; const table = new Table(arrayData, { header: { order: [2, 1, 0, 4, 3, 5, 'id2', '#'], origin: true, displayNames: { 0: 'ID', 1: 'First Name', 2: 'Last Name', 3: 'Email', 4: 'Gender', 5: 'Birth Date' }, dynamic: { id2: (row) => row[0] * 2 } }, sort: { columns: ['#'], directions: ['desc'] } }); table.print(); // Renders array data with custom column names, reordered columns, and origin index ``` -------------------------------- ### Table Accumulation Functions for Sales Data (JavaScript) Source: https://context7.com/larswaechter/voici.js/llms.txt This example shows how to compute statistical aggregations for columns in a table and display them as a summary row. It utilizes the `accumulation` option with `AccumulationFunction.SUM` to calculate totals for quarterly sales data. Requires `voici.js` and `AccumulationFunction`. ```javascript import { Table, AccumulationFunction } from 'voici.js'; const salesData = [ { product: 'Product A', q1: 1200, q2: 1500, q3: 1350, q4: 1800 }, { product: 'Product B', q1: 800, q2: 950, q3: 1100, q4: 1250 }, { product: 'Product C', q1: 2000, q2: 1800, q3: 2100, q4: 2300 }, { product: 'Product D', q1: 450, q2: 520, q3: 480, q4: 610 } ]; const table = new Table(salesData, { body: { accumulation: { separator: '=', bgColor: '#2ECC71', columns: { q1: AccumulationFunction.SUM, q2: AccumulationFunction.SUM, q3: AccumulationFunction.SUM, q4: AccumulationFunction.SUM } } }, header: { displayNames: { q1: 'Q1 Sales', q2: 'Q2 Sales', q3: 'Q3 Sales', q4: 'Q4 Sales' } } }); table.print(); // Displays quarterly sales with total sums for each quarter at the bottom ``` -------------------------------- ### Access Table Cell Data and Dimensions with voici.js Source: https://context7.com/larswaechter/voici.js/llms.txt Retrieves individual cell values from a table dataset using `getDataCell`, gets table dimensions with `shape`, and lists column names using `columns`. Assumes `voici.js` is installed and imported. ```javascript import { Table } from 'voici.js'; interface DynamicCols { fullName: string; } const people = [ { firstName: 'John', lastName: 'Doe', age: 30 }, { firstName: 'Jane', lastName: 'Smith', age: 28 }, { firstName: 'Bob', lastName: 'Johnson', age: 35 } ]; const table = new Table(people, { header: { dynamic: { fullName: (row) => `${row.firstName} ${row.lastName}` } } }); // Access cell data const firstName = table.getDataCell(0, 'firstName'); // 'John' const age = table.getDataCell(1, 'age'); // 28 const dynamicValue = table.getDataCell(2, 'fullName'); // 'Bob Johnson' // Get table dimensions const [rows, cols] = table.shape; // [3, 4] // Get column names const columns = table.columns; // ['firstName', 'lastName', 'age', 'fullName'] console.log(`Table has ${rows} rows and ${cols} columns`); console.log(`Columns: ${columns.join(', ')}`); ``` -------------------------------- ### Get Config Interface in TypeScript Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Defines the TypeScript interface for retrieving configuration options. It specifies the structure and types for various table display properties, including alignment, body styling, header customization, and sorting. This interface is crucial for type-safe configuration management. ```typescript interface Config { align?: "LEFT" | "CENTER" | "RIGHT"; bgColorColumns?: string[]; body?: Partial<{ accumulation?: Partial<{ bgColor: string; columns: Partial>; separator: string; }>; bgColor: string; fillEmpty?: Partial>>; filterRow?: (row: DatasetRow, index: number) => boolean; highlightCell?: Partial<{ bold: boolean; func: (content: unknown, row: number, col: InferAttributes) => boolean; italic: boolean; textColor: string; underline: boolean; }>; highlightRow?: Partial<{ bgColor: string; func: (row: DatasetRow, index: number) => boolean; }>; peek: number | [number, number]; precision: number; striped: boolean; subset: [number?, number?]; textColor: string; }>; border?: Partial<{ color: string; groupSize: number; horizontal: string; vertical: string; }>; header?: Partial<{ bgColor: string; bold: boolean; displayNames: Partial< { [key in InferRowAttributesOrigin]: string }>; dynamic: DynamicColumn; exclude: InferRowAttributes[]; include: InferRowAttributes[]; italic: boolean; lowercase: boolean; maxWidth: number | "auto"; order: InferAttributesOrigin[]; origin: boolean; separator: string; textColor: string; underline: boolean; uppercase: boolean; upperfirst: boolean; visible: boolean; width: number | "auto" | "stretch"; }>; padding?: Partial<{ char: string; size: number }>; sort: Sort>; } // Example usage (assuming TRow, TDColumns, Accumulation, FillEmptyOption, DatasetRow, DynamicColumn, InferAttributes, InferRowAttributesOrigin, InferRowAttributes, Sort are defined elsewhere) // const defaultConfig: Required> = { // align: "LEFT", // bgColorColumns: [], // body: { // accumulation: {}, // bgColor: "#ffffff", // fillEmpty: {}, // highlightCell: {}, // highlightRow: {}, // peek: 5, // precision: 2, // striped: false, // subset: [], // textColor: "#000000" // }, // border: {}, // header: {}, // padding: {}, // sort: {} as Sort // }; ``` -------------------------------- ### Select Data Subsets for Table Display Source: https://context7.com/larswaechter/voici.js/llms.txt Allows for the selection of a specific range of rows from the dataset to be displayed in the table. The 'subset' option in the body configuration accepts an array of two numbers, defining the start and end indices (exclusive of the end index) of the desired data slice, similar to JavaScript's `Array.prototype.slice()`. ```javascript import { Table } from 'voici.js'; const transactions = Array.from({ length: 50 }, (_, i) => ({ txId: 1000 + i, amount: (Math.random() * 500).toFixed(2), date: new Date(2024, 0, i + 1) })); const table = new Table(transactions, { body: { subset: [10, 20] // Display rows 10-19 (like array.slice) }, header: { displayNames: { txId: 'Transaction ID', amount: 'Amount ($)', date: 'Date' } } }); table.print(); // Shows only transactions from index 10 to 19 ``` -------------------------------- ### Get Table Shape Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Retrieves the dimensions of the table, returned as a tuple containing the number of rows and columns. This getter is defined in table.ts. ```typescript get shape(): [rows: number, columns: number] ``` -------------------------------- ### Get Table Dataset Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Retrieves the current dataset of the table. The dataset is an array of DatasetRow objects, each representing a row with its associated data and column information. This getter is defined in table.ts. ```typescript get dataset(): DatasetRow[] ``` -------------------------------- ### Get Cell Data (TypeScript) Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Retrieves the value of a specific cell within the dataset. Requires the row and column indices as input. The return type is a generic AccumulationRow, dependent on the dataset's row and column types. ```typescript getDataCell(row: number, col: InferDatasetRowAttributesOrigin): AccumulationRow[InferDatasetRowAttributesOrigin] ``` -------------------------------- ### Theme Management Source: https://github.com/larswaechter/voici.js/blob/main/docs/types/Accumulation.html Handles theme persistence and application using localStorage and DOM manipulation. ```APIDOC ## Theme Management ### Description This JavaScript code snippet manages the theme of the application by reading the theme preference from `localStorage` and applying it to the `documentElement`. It also includes a mechanism to hide the body initially and display it after the application is ready or after a short delay. ### Method JavaScript (Client-side) ### Endpoint N/A (Client-side script) ### Parameters N/A ### Request Body N/A ### Request Example ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app ? app.showPage() : document.body.style.removeProperty("display"), 500); ``` ### Response N/A (Client-side script execution) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Set Theme and Initial Display Logic (JavaScript) Source: https://github.com/larswaechter/voici.js/blob/main/docs/hierarchy.html This snippet configures the document's theme based on local storage and controls the initial display of the body. It sets the 'data-theme' attribute on the document element and uses a timeout to conditionally show the application's page or remove the display style from the body. Dependencies include localStorage and a potential global 'app' object. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Basic Table Printing with voici.js Source: https://github.com/larswaechter/voici.js/blob/main/README.md This JavaScript code snippet demonstrates the basic usage of voici.js. It imports the `Table` class, defines a sample dataset, creates a new `Table` instance with the data, and then prints the formatted table to the console. ```javascript import { Table } from 'voici.js'; const data = [ { firstname: 'Homer', lastname: 'Simpson', age: 39 }, { firstname: 'Marge', lastname: 'Simpson', age: 36 }, { firstname: 'Bart', lastname: 'Simpson', age: 10 }, { firstname: 'Lisa', lastname: 'Simpson', age: 8 }, { firstname: 'Maggie', lastname: 'Simpson', age: 1 } ]; const table = new Table(data); table.print(); ``` -------------------------------- ### Table Configuration Options Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Defines various configuration options for a table, including background and text colors, fill and highlight settings for cells and rows, border styles, header customizations, and padding. It also includes options for precision, striping, subsetting data, and sorting. ```typescript { bgColor: string; fillEmpty: Partial>>; filterRow: (row: DatasetRow, index: number) => boolean; highlightCell: Partial<{ bold: boolean; func: (content: unknown, row: number, col: InferAttributes) => boolean; italic: boolean; textColor: string; underline: boolean; }>; highlightRow: Partial<{ bgColor: string; func: (row: DatasetRow, index: number) => boolean; }>; peek: number | [number, number]; precision: number; striped: boolean; subset: [number?, number?]; textColor: string; border: Partial<{ color: string; groupSize: number; horizontal: string; vertical: string; }>; header: Partial<{ bgColor: string; bold: boolean; displayNames: Partial< { [key in InferRowAttributesOrigin]: string } >; dynamic: DynamicColumn; exclude: InferRowAttributes[]; include: InferRowAttributes[]; italic: boolean; lowercase: boolean; maxWidth: number | "auto"; order: InferAttributesOrigin[]; origin: boolean; separator: string; textColor: string; underline: boolean; uppercase: boolean; upperfirst: boolean; visible: boolean; width: number | "auto" | "stretch"; }>; padding: Partial<{ char: string; size: number }>; sort: [Sort>]; } ``` -------------------------------- ### Table Configuration Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Defines the various configuration options available for styling and customizing the table, including border, header, padding, and sorting. ```APIDOC ## Table Configuration Options ### Description This section details the extensive configuration options for customizing the appearance and behavior of the table. ### Parameters #### Request Body - **border** (Partial<{ color: string; groupSize: number; horizontal: string; vertical: string; }>) - Optional - Defines border styles for the table. - **header** (Partial<{ bgColor: string; bold: boolean; displayNames: Partial<{ [key in InferRowAttributesOrigin]: string }>; dynamic: DynamicColumn; exclude: InferRowAttributes[]; include: InferRowAttributes[]; italic: boolean; lowercase: boolean; maxWidth: number | "auto"; order: InferAttributesOrigin[]; origin: boolean; separator: string; textColor: string; underline: boolean; uppercase: boolean; upperfirst: boolean; visible: boolean; width: number | "auto" | "stretch"; }>) - Optional - Configures header styles and behavior. - **padding** (Partial<{ char: string; size: number }>) - Optional - Sets padding for table cells. - **sort** (Sort>) - Optional - Specifies sorting configurations for the table. - **bgColor** (string) - Optional - Background color for the table. - **fillEmpty** (Partial>>) - Optional - Options for filling empty cells. - **filterRow** ((row: DatasetRow, index: number) => boolean) - Optional - A function to filter rows based on specified criteria. - **highlightCell** (Partial<{ bold: boolean; func: (content: unknown, row: number, col: InferAttributes) => boolean; italic: boolean; textColor: string; underline: boolean; }>) - Optional - Styles for highlighting individual cells. - **highlightRow** (Partial<{ bgColor: string; func: (row: DatasetRow, index: number) => boolean; }>) - Optional - Styles for highlighting entire rows. - **peek** (number | [number, number]) - Optional - Controls the peek behavior of the table. - **precision** (number) - Optional - Sets the precision for numerical display. - **striped** (boolean) - Optional - Enables or disables striped rows. - **subset** ([number?, number?]) - Optional - Defines a subset of rows and columns to display. - **textColor** (string) - Optional - Default text color for the table. ``` -------------------------------- ### Add Dynamic Columns to Table in Node.js Source: https://context7.com/larswaechter/voici.js/llms.txt Illustrates how to add computed columns to a table based on existing data using transformation functions in voici.js. This enables creating columns like 'total' or 'discounted price' dynamically. ```javascript import { Table } from 'voici.js'; interface DynamicColumns { total: number; discounted: number; } const orders = [ { orderId: 1001, quantity: 5, unitPrice: 25.50 }, { orderId: 1002, quantity: 3, unitPrice: 49.99 }, { orderId: 1003, quantity: 10, unitPrice: 15.00 } ]; const table = new Table(orders, { header: { order: ['orderId', 'quantity', 'unitPrice', 'total', 'discounted'], displayNames: { orderId: 'Order ID', unitPrice: 'Unit Price', total: 'Total', discounted: '10% Off' }, dynamic: { total: (row) => row.quantity * row.unitPrice, discounted: (row) => row.quantity * row.unitPrice * 0.9 } }, body: { precision: 2 } }); table.print(); ``` -------------------------------- ### Dataset API Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Provides methods for accessing and setting the dataset of the table. ```APIDOC ## Dataset API ### Description This API allows you to get and set the dataset for the table. ### GET /dataset #### Description Retrieves the current dataset of the table. ### Method GET ### Endpoint `/dataset` #### Returns - **dataset** (DatasetRow[]) - An array of row objects representing the table data. ### SET /dataset #### Description Sets or updates the dataset for the table. ### Method SET ### Endpoint `/dataset` #### Parameters ##### Request Body - **dataset** (DatasetRow[]) - Required - The new dataset to be applied to the table. ``` -------------------------------- ### Print Plain Table to Console (TypeScript) Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Prints the table to the console without any applied styling. This method provides a raw, unformatted view of the table data. ```typescript printPlain(): void ``` -------------------------------- ### Highlight Cells and Rows in a Table (JavaScript) Source: https://context7.com/larswaechter/voici.js/llms.txt This snippet demonstrates how to highlight specific cells or entire rows in a table based on custom conditions. It uses the `highlightCell` and `highlightRow` options to apply text and background styling. Dependencies include the `voici.js` library. ```javascript import { Table } from 'voici.js'; const inventory = [ { item: 'Widget A', quantity: 150, reorderLevel: 100, price: 25.99 }, { item: 'Widget B', quantity: 45, reorderLevel: 100, price: 35.50 }, { item: 'Widget C', quantity: 200, reorderLevel: 150, price: 18.75 }, { item: 'Widget D', quantity: 15, reorderLevel: 50, price: 42.00 } ]; const table = new Table(inventory, { body: { highlightCell: { func: (content, row, col) => { if (col === 'quantity') { const rowData = inventory[row]; return rowData.quantity < rowData.reorderLevel; } return false; }, textColor: '#FF0000', bold: true, underline: true }, highlightRow: { func: (row) => row.quantity < 20, bgColor: '#FFFF00' } } }); table.print(); // Highlights low-stock quantities in red and critical items with yellow background ``` -------------------------------- ### Export Table Data to File and as Strings Source: https://context7.com/larswaechter/voici.js/llms.txt Enables exporting table content to a text file without styling for further processing, or retrieving it as plain or styled strings. The `exportFile` method writes the table to a specified path, while `toPlainString` and `toString` return the content as unformatted and formatted strings, respectively. ```javascript import { Table } from 'voici.js'; const reportData = [ { date: '2024-01-01', revenue: 12500, expenses: 8300, profit: 4200 }, { date: '2024-01-02', revenue: 15200, expenses: 9100, profit: 6100 }, { date: '2024-01-03', revenue: 13800, expenses: 8900, profit: 4900 } ]; const table = new Table(reportData, { header: { displayNames: { date: 'Date', revenue: 'Revenue ($)', expenses: 'Expenses ($)', profit: 'Profit ($)' } }, body: { accumulation: { columns: { revenue: AccumulationFunction.SUM, expenses: AccumulationFunction.SUM, profit: AccumulationFunction.SUM } } } }); // Export to file table.exportFile('./report.txt', 'w'); // Get as plain string without file writing const plainString = table.toPlainString(); console.log(plainString); // Get as styled string for terminal const styledString = table.toString(); console.log(styledString); ``` -------------------------------- ### Export Table to File (TypeScript) Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Exports the plain table data to a specified file path. This method does not include advanced styling. It accepts an optional 'mode' parameter to control how the file is opened (defaults to 'w' for write). ```typescript exportFile(filepath: string, mode?: OpenMode): void ``` -------------------------------- ### Statistical Analysis with Mean Accumulation (JavaScript) Source: https://context7.com/larswaechter/voici.js/llms.txt This snippet demonstrates applying statistical functions, specifically the arithmetic mean (`AccumulationFunction.MEAN`), to analyze numeric data across columns in a table. It includes options for precision and custom separators. Dependencies: `voici.js`, `AccumulationFunction`. ```javascript import { Table, AccumulationFunction } from 'voici.js'; const testScores = [ { student: 'Alice', math: 95, science: 88, english: 92 }, { student: 'Bob', math: 78, science: 85, english: 80 }, { student: 'Charlie', math: 92, science: 90, english: 88 }, { student: 'Diana', math: 85, science: 92, english: 95 }, { student: 'Eve', math: 88, science: 86, english: 91 } ]; const table = new Table(testScores, { body: { accumulation: { separator: '─', bgColor: '#3498DB', columns: { math: AccumulationFunction.MEAN, science: AccumulationFunction.MEAN, english: AccumulationFunction.MEAN } }, precision: 2 } }); table.print(); // Shows student scores with average (mean) scores for each subject // Available accumulation functions: // COUNT - Number of non-empty values // FREQ - Most frequent value // INFREQ - Least frequent value // MAX - Maximum value // MIN - Minimum value // MEAN - Arithmetic mean // MEDIAN - Middle value // GEO_MEAN - Geometric mean // HARM_MEAN - Harmonic mean // SUM - Sum of all values // RANGE - Difference between max and min // STD - Standard deviation // VAR - Variance ``` -------------------------------- ### Fill Empty Cells with Custom Functions in Table Source: https://context7.com/larswaechter/voici.js/llms.txt Provides fallback values for cells that are empty or null by utilizing custom functions. The 'fillEmpty' option within the body configuration maps column names to functions that receive the current row and return a value to fill the empty cell. This is useful for handling missing data gracefully. ```javascript import { Table } from 'voici.js'; const incompleteData = [ { name: 'Alice', department: 'Engineering', salary: 95000, bonus: null }, { name: 'Bob', department: null, salary: 65000, bonus: 5000 }, { name: 'Charlie', department: 'Sales', salary: null, bonus: 8000 }, { name: 'Diana', department: 'Marketing', salary: 75000, bonus: null } ]; const table = new Table(incompleteData, { body: { fillEmpty: { department: (row) => 'Unassigned', salary: (row) => 0, bonus: (row) => Math.floor(row.salary * 0.1) } } }); table.print(); // Fills missing departments with 'Unassigned', missing salaries with 0, // and calculates missing bonuses as 10% of salary ``` -------------------------------- ### Enable Peek Mode for Large Datasets in Table Source: https://context7.com/larswaechter/voici.js/llms.txt Optimizes the display of large datasets by showing only the first and last N rows, with a placeholder indicating omitted rows. This is controlled by the 'peek' option within the table's body configuration. It can accept a single number for symmetric display or an array for asymmetric display of first and last rows. ```javascript import { Table } from 'voici.js'; const largeDataset = Array.from({ length: 100 }, (_, i) => ({ id: i + 1, name: `Item ${i + 1}`, value: Math.random() * 1000 })); const table = new Table(largeDataset, { body: { peek: 5 // Show first 5 and last 5 rows // Or use array: peek: [3, 7] for first 3 and last 7 }, header: { displayNames: { id: 'ID', name: 'Name', value: 'Value' } }, body: { precision: 2 } }); table.print(); // Shows first 5 and last 5 rows with <---> separator for omitted rows ``` -------------------------------- ### Config Type Alias Source: https://github.com/larswaechter/voici.js/blob/main/docs/types/Config.html Detailed documentation for the Config type alias used in voici.js. This covers various aspects of table configuration, including body, border, header, and styling options. ```APIDOC ## Type Alias: Config ### Description Configuration type for voici.js, allowing extensive customization of table appearance and behavior. ### Type Parameters * `TRow` extends `Row` * `TDColumns` extends `object` = `never` ### Properties #### `align` (string) Alignment for table cells. Possible values: "LEFT", "CENTER", "RIGHT". #### `bgColorColumns` (string[]) Array of background colors for specific columns. #### `body` (object) Configuration for the table body. * `accumulation` (object) * `bgColor` (string) * `columns` (object): Configuration for accumulated columns. * `separator` (string) * `bgColor` (string) * `fillEmpty` (object) * `filterRow` (function) * `highlightCell` (object) * `bold` (boolean) * `func` (function) * `italic` (boolean) * `textColor` (string) * `underline` (boolean) * `highlightRow` (object) * `bgColor` (string) * `func` (function) * `peek` (number | [number, number]) * `precision` (number) * `striped` (boolean) * `subset` ([number?, number?]) * `textColor` (string) #### `border` (object) Configuration for table borders. * `color` (string) * `groupSize` (number) * `horizontal` (string) * `vertical` (string) #### `header` (object) Configuration for the table header. * `bgColor` (string) * `bold` (boolean) * `displayNames` (object): Mapping for custom display names of columns. * `dynamic` (object): Configuration for dynamic columns. * `exclude` (array) * `include` (array) * `italic` (boolean) * `lowercase` (boolean) * `maxWidth` (number | "auto") * `order` (array) * `origin` (boolean) * `separator` (string) * `textColor` (string) * `underline` (boolean) * `uppercase` (boolean) * `upperfirst` (boolean) * `visible` (boolean) * `width` (number | "auto" | "stretch") #### `padding` (object) Configuration for cell padding. * `char` (string) * `size` (number) #### `sort` (object) Configuration for sorting behavior. ### Source * Defined in `config.ts:94` ``` -------------------------------- ### Print Table to Console (TypeScript) Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Prints the table to the console. An optional boolean parameter 'clear' can be provided to clear the console before printing the table. Defaults to false. ```typescript print(clear?: boolean): void ``` -------------------------------- ### Stringify Data Types with voici.js Helper Function Source: https://context7.com/larswaechter/voici.js/llms.txt Demonstrates the usage of the `stringify` helper function from `voici.js` to convert basic and complex data types into their string representations. This function is automatically used by `voici.js` for displaying data in tables. ```javascript import { stringify, Table } from 'voici.js'; // Basic types console.log(stringify('Hello')); // 'Hello' console.log(stringify(42)); // '42' console.log(stringify(null)); // '' console.log(stringify(undefined)); // '' console.log(stringify(NaN)); // '' // Complex types console.log(stringify(new Date(2024, 0, 1))); // 'Mon Jan 01 2024' console.log(stringify({ a: 1, b: 2 })); // '{"a":1,"b":2}' console.log(stringify([1, 2, 3])); // '[1,2,3]' console.log(stringify(new Set([1, 2, 3]))); // '[1,2,3]' console.log(stringify(new Map([['a', 1]]))); // '[["a",1]]' // Use in custom scenarios const customData = [ { value: new Set([1, 2, 3]) }, { value: new Map([['key', 'val']]) }, { value: { nested: 'object' } } ]; const table = new Table(customData); table.print(); // All complex types are automatically stringified using this function ``` -------------------------------- ### Convert Table to Plain String (TypeScript) Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Converts the table data into a plain string format without any styling. This is useful for saving the table to a file or for pasting it as plain text elsewhere. ```typescript toPlainString(): string ``` -------------------------------- ### Convert Table to String (TypeScript) Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Converts the table data into a string format, typically used for console output. This method may include styling information depending on the table's configuration. ```typescript toString(): string ``` -------------------------------- ### Sort and Filter Table Data in Node.js Source: https://context7.com/larswaechter/voici.js/llms.txt Demonstrates sorting table rows by specified columns and filtering rows based on custom conditions using voici.js. This feature allows for targeted data presentation and analysis directly in the terminal. ```javascript import { Table } from 'voici.js'; const employees = [ { name: 'Alice', department: 'Engineering', salary: 95000, years: 5 }, { name: 'Bob', department: 'Sales', salary: 65000, years: 3 }, { name: 'Charlie', department: 'Engineering', salary: 120000, years: 8 }, { name: 'Diana', department: 'Marketing', salary: 75000, years: 4 }, { name: 'Eve', department: 'Engineering', salary: 85000, years: 2 } ]; const table = new Table(employees, { sort: { columns: ['department', 'salary'], directions: ['asc', 'desc'] }, body: { filterRow: (row) => row.department === 'Engineering' && row.salary > 80000 }, header: { bold: true, separator: '=' } }); table.print(); ``` -------------------------------- ### Exclude Columns and Customize Display Names in Table Source: https://context7.com/larswaechter/voici.js/llms.txt Controls which columns are displayed in a table and allows for custom header labels for specific columns. It takes an array of column names to exclude and an object mapping original column names to their desired display names. The order of columns can also be specified. ```javascript import { Table } from 'voici.js'; const users = [ { id: 1, username: 'alice', password: 'secret123', email: 'alice@example.com', role: 'admin' }, { id: 2, username: 'bob', password: 'pass456', email: 'bob@example.com', role: 'user' }, { id: 3, username: 'charlie', password: 'pwd789', email: 'charlie@example.com', role: 'user' } ]; const table = new Table(users, { header: { exclude: ['password'], displayNames: { id: 'User ID', username: 'Username', email: 'Email Address', role: 'Role' }, order: ['id', 'username', 'email', 'role'] } }); table.print(); // Displays user data without the password column and with custom headers ``` -------------------------------- ### AccumulationFunction Enumeration Source: https://github.com/larswaechter/voici.js/blob/main/docs/enums/AccumulationFunction.html This enumeration defines various statistical accumulation functions used in the voici.js library. Each member represents a different method for calculating a single value from a set of data points. ```APIDOC ## Enumeration: AccumulationFunction This enumeration defines various statistical accumulation functions used in the voici.js library. Each member represents a different method for calculating a single value from a set of data points. ### Enumeration Members * **COUNT**: 0 * Description: The number of values (non-empty cells). * Defined in: `accumulation.ts:13` * **FREQ**: 1 * Description: The most frequent value. * Defined in: `accumulation.ts:16` * **GEO_MEAN**: 2 * Description: The geometric mean. * Defined in: `accumulation.ts:19` * **HARM_MEAN**: 3 * Description: The harmonic mean. * Defined in: `accumulation.ts:22` * **INFREQ**: 4 * Description: The most infrequent value. * Defined in: `accumulation.ts:25` * **MAX**: 5 * Description: The maximum value. * Defined in: `accumulation.ts:28` * **MEAN**: 6 * Description: The mean. * Defined in: `accumulation.ts:31` * **MEDIAN**: 7 * Description: The median. * Defined in: `accumulation.ts:34` * **MIN**: 8 * Description: The minimal value. * Defined in: `accumulation.ts:37` * **RANGE**: 9 * Description: The difference between min and max. * Defined in: `accumulation.ts:40` * **STD**: 10 * Description: The standard deviation. * Defined in: `accumulation.ts:43` * **SUM**: 11 * Description: The sum. * Defined in: `accumulation.ts:46` * **VAR**: 12 * Description: The variance. * Defined in: `accumulation.ts:49` ``` -------------------------------- ### Set Table Dataset Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Sets or updates the dataset for the table. This method accepts an array of DatasetRow objects. It is defined in table.ts and returns void. ```typescript set dataset(dataset: DatasetRow[]) ``` -------------------------------- ### Shape API Source: https://github.com/larswaechter/voici.js/blob/main/docs/classes/Table.html Provides a method to retrieve the dimensions (rows and columns) of the table. ```APIDOC ## Shape API ### Description This API allows you to get the shape (dimensions) of the table. ### GET /shape #### Description Retrieves the number of rows and columns in the table. ### Method GET ### Endpoint `/shape` #### Returns - **shape** ([rows: number, columns: number]) - An array containing the number of rows and columns. ```