diff --git a/docs/api/advanced-features.md b/docs/api/advanced-features.md new file mode 100644 index 00000000..51d216dd --- /dev/null +++ b/docs/api/advanced-features.md @@ -0,0 +1,598 @@ +--- +id: advanced-features +title: Advanced Features +sidebar_label: Advanced Features +--- + +# Advanced Features + +This section covers advanced features and techniques for complex table operations. + +## Computed Columns + +Computed columns allow you to create new columns based on calculations or transformations of existing data. + +### Basic Computed Columns + +```javascript +const { Table } = require("console-table-printer"); + +const table = new Table({ + columns: [ + { name: "price", alignment: "right" }, + { name: "quantity", alignment: "right" } + ], + computedColumns: [ + { + name: "total", + function: (row) => row.price * row.quantity + } + ] +}); + +table.addRows([ + { price: 10.50, quantity: 3 }, + { price: 25.00, quantity: 2 }, + { price: 5.75, quantity: 5 } +]); + +table.printTable(); +``` + +### Using Row Index + +```javascript +const table = new Table({ + columns: [ + { name: "name", alignment: "left" }, + { name: "score", alignment: "right" } + ], + computedColumns: [ + { + name: "rank", + function: (row, index) => `#${index + 1}` + }, + { + name: "percentage", + function: (row, index, array) => { + const maxScore = Math.max(...array.map(r => r.score)); + return `${((row.score / maxScore) * 100).toFixed(1)}%`; + } + } + ] +}); + +table.addRows([ + { name: "Alice", score: 85 }, + { name: "Bob", score: 92 }, + { name: "Charlie", score: 78 } +]); + +table.printTable(); +``` + +### Complex Computations + +```javascript +const table = new Table({ + columns: [ + { name: "name", alignment: "left" }, + { name: "math", alignment: "right" }, + { name: "science", alignment: "right" }, + { name: "english", alignment: "right" } + ], + computedColumns: [ + { + name: "average", + function: (row) => { + const scores = [row.math, row.science, row.english]; + return (scores.reduce((a, b) => a + b, 0) / scores.length).toFixed(1); + } + }, + { + name: "grade", + function: (row) => { + const avg = parseFloat(row.average); + if (avg >= 90) return "A"; + if (avg >= 80) return "B"; + if (avg >= 70) return "C"; + if (avg >= 60) return "D"; + return "F"; + } + }, + { + name: "status", + function: (row, index, array) => { + const avg = parseFloat(row.average); + const classAvg = array.reduce((sum, r) => sum + parseFloat(r.average), 0) / array.length; + return avg > classAvg ? "Above Average" : "Below Average"; + } + } + ] +}); + +table.addRows([ + { name: "Alice", math: 85, science: 90, english: 88 }, + { name: "Bob", math: 92, science: 88, english: 85 }, + { name: "Charlie", math: 78, science: 82, english: 80 } +]); + +table.printTable(); +``` + +## Custom Styling + +### Custom Border Styles + +```javascript +const table = new Table({ + style: { + headerTop: { + left: "┌", + mid: "┬", + right: "┐", + other: "─" + }, + headerBottom: { + left: "├", + mid: "┼", + right: "┤", + other: "─" + }, + tableBottom: { + left: "└", + mid: "┴", + right: "┘", + other: "─" + }, + vertical: "│" + }, + columns: [ + { name: "id", alignment: "left" }, + { name: "name", alignment: "center" }, + { name: "age", alignment: "right" } + ] +}); + +table.addRows([ + { id: 1, name: "John", age: 25 }, + { id: 2, name: "Jane", age: 30 } +]); + +table.printTable(); +``` + +### Colored Borders with Chalk + +```javascript +const chalk = require('chalk'); + +const table = new Table({ + style: { + headerTop: { + left: chalk.blue("╔"), + mid: chalk.blue("╦"), + right: chalk.blue("╗"), + other: chalk.blue("═") + }, + headerBottom: { + left: chalk.blue("╟"), + mid: chalk.blue("╬"), + right: chalk.blue("╢"), + other: chalk.blue("═") + }, + tableBottom: { + left: chalk.blue("╚"), + mid: chalk.blue("╩"), + right: chalk.blue("╝"), + other: chalk.blue("═") + }, + vertical: chalk.blue("║") + }, + columns: [ + { name: "id", alignment: "left", color: "cyan" }, + { name: "name", alignment: "center", color: "yellow" }, + { name: "age", alignment: "right", color: "green" } + ] +}); + +table.addRows([ + { id: 1, name: "John", age: 25 }, + { id: 2, name: "Jane", age: 30 } +]); + +table.printTable(); +``` + +## Custom Color Mapping + +### Semantic Colors + +```javascript +const table = new Table({ + colorMap: { + success: '\x1b[32m', // Green + error: '\x1b[31m', // Red + warning: '\x1b[33m', // Yellow + info: '\x1b[36m', // Cyan + highlight: '\x1b[1m', // Bold + dim: '\x1b[2m', // Dim + underline: '\x1b[4m', // Underline + critical: '\x1b[1m\x1b[31m' // Bold Red + }, + columns: [ + { name: "id", alignment: "left" }, + { name: "status", alignment: "center" }, + { name: "message", alignment: "left" } + ] +}); + +table.addRows([ + { id: 1, status: "success", message: "Operation completed" }, + { id: 2, status: "error", message: "Failed to connect" }, + { id: 3, status: "warning", message: "Low disk space" }, + { id: 4, status: "critical", message: "System crash detected" } +]); + +table.printTable(); +``` + +### Conditional Coloring + +```javascript +const table = new Table({ + columns: [ + { name: "name", alignment: "left" }, + { name: "score", alignment: "right" }, + { name: "status", alignment: "center" } + ] +}); + +const data = [ + { name: "Alice", score: 95 }, + { name: "Bob", score: 75 }, + { name: "Charlie", score: 60 }, + { name: "David", score: 45 } +]; + +data.forEach(row => { + let color = "white"; + let status = "Pass"; + + if (row.score >= 90) { + color = "green"; + status = "Excellent"; + } else if (row.score >= 80) { + color = "cyan"; + status = "Good"; + } else if (row.score >= 70) { + color = "yellow"; + status = "Average"; + } else if (row.score >= 60) { + color = "red"; + status = "Poor"; + } else { + color = "magenta"; + status = "Fail"; + } + + table.addRow( + { name: row.name, score: row.score, status: status }, + { color: color } + ); +}); + +table.printTable(); +``` + +## Performance Optimization + +### Large Dataset Handling + +```javascript +const table = new Table({ + // Pre-define columns for better performance + columns: [ + { name: "id", alignment: "left" }, + { name: "name", alignment: "center" }, + { name: "email", alignment: "left" }, + { name: "status", alignment: "center" } + ], + + // Filter data before adding to table + filter: (row) => row.status === "active", + + // Sort efficiently + sort: (row1, row2) => row1.name.localeCompare(row2.name) +}); + +// Process data in chunks for large datasets +async function processLargeDataset(data) { + const chunkSize = 1000; + + for (let i = 0; i < data.length; i += chunkSize) { + const chunk = data.slice(i, i + chunkSize); + + // Process chunk + const processedChunk = chunk.map(row => ({ + ...row, + email: row.email.toLowerCase(), + status: row.active ? "active" : "inactive" + })); + + // Add to table + table.addRows(processedChunk); + + // Optional: Print progress + console.log(`Processed ${Math.min(i + chunkSize, data.length)} of ${data.length} records`); + } + + table.printTable(); +} +``` + +### Memory-Efficient Computed Columns + +```javascript +const table = new Table({ + columns: [ + { name: "id", alignment: "left" }, + { name: "value", alignment: "right" } + ], + computedColumns: [ + { + name: "running_total", + function: (row, index, array) => { + // Calculate running total efficiently + return array + .slice(0, index + 1) + .reduce((sum, r) => sum + r.value, 0); + } + } + ] +}); + +// For very large datasets, consider pre-calculating +function preCalculateRunningTotal(data) { + let runningTotal = 0; + return data.map(row => ({ + ...row, + running_total: runningTotal += row.value + })); +} +``` + +## Advanced Filtering and Sorting + +### Multi-Level Sorting + +```javascript +const table = new Table({ + columns: [ + { name: "department", alignment: "left" }, + { name: "name", alignment: "left" }, + { name: "salary", alignment: "right" } + ], + sort: (row1, row2) => { + // First sort by department + const deptCompare = row1.department.localeCompare(row2.department); + if (deptCompare !== 0) return deptCompare; + + // Then sort by salary (descending) + return row2.salary - row1.salary; + } +}); + +table.addRows([ + { department: "Engineering", name: "Alice", salary: 85000 }, + { department: "Engineering", name: "Bob", salary: 90000 }, + { department: "Marketing", name: "Charlie", salary: 70000 }, + { department: "Marketing", name: "David", salary: 75000 }, + { department: "Sales", name: "Eve", salary: 65000 } +]); + +table.printTable(); +``` + +### Complex Filtering + +```javascript +const table = new Table({ + columns: [ + { name: "id", alignment: "left" }, + { name: "name", alignment: "left" }, + { name: "age", alignment: "right" }, + { name: "department", alignment: "left" }, + { name: "salary", alignment: "right" } + ], + filter: (row) => { + // Multiple conditions + const isAdult = row.age >= 18; + const isHighSalary = row.salary >= 50000; + const isEngineering = row.department === "Engineering"; + + // Complex logic + return isAdult && (isHighSalary || isEngineering); + } +}); + +table.addRows([ + { id: 1, name: "Alice", age: 25, department: "Engineering", salary: 85000 }, + { id: 2, name: "Bob", age: 17, department: "Marketing", salary: 45000 }, + { id: 3, name: "Charlie", age: 30, department: "Sales", salary: 60000 }, + { id: 4, name: "David", age: 22, department: "Engineering", salary: 40000 } +]); + +table.printTable(); +``` + +## Dynamic Table Building + +### API Data Integration + +```javascript +async function buildUserTable() { + const table = new Table({ + title: "User Directory", + style: "fatBorder" + }); + + try { + // Fetch data from API + const response = await fetch('https://api.example.com/users'); + const users = await response.json(); + + // Determine columns dynamically + const sampleUser = users[0]; + const columns = Object.keys(sampleUser).map(key => ({ + name: key, + alignment: typeof sampleUser[key] === 'number' ? 'right' : 'left', + color: key === 'status' ? 'yellow' : 'white' + })); + + // Add columns + table.addColumns(columns); + + // Add rows with conditional styling + users.forEach((user, index) => { + const options = {}; + + // Color based on status + if (user.status === 'active') { + options.color = 'green'; + } else if (user.status === 'inactive') { + options.color = 'red'; + } + + // Add separator every 10 users + if ((index + 1) % 10 === 0) { + options.separator = true; + } + + table.addRow(user, options); + }); + + table.printTable(); + + } catch (error) { + console.error('Failed to build table:', error); + } +} +``` + +### Real-time Data Updates + +```javascript +class LiveTable { + constructor() { + this.table = new Table({ + columns: [ + { name: "timestamp", alignment: "left" }, + { name: "event", alignment: "left" }, + { name: "status", alignment: "center" } + ], + title: "Live Event Log" + }); + } + + addEvent(event, status) { + const timestamp = new Date().toLocaleTimeString(); + + let color = "white"; + if (status === "success") color = "green"; + else if (status === "error") color = "red"; + else if (status === "warning") color = "yellow"; + + this.table.addRow( + { timestamp, event, status }, + { color, separator: status === "error" } + ); + + // Clear console and re-render + console.clear(); + this.table.printTable(); + } +} + +// Usage +const liveTable = new LiveTable(); + +// Simulate real-time events +setInterval(() => { + const events = ["Data processed", "User logged in", "File uploaded"]; + const statuses = ["success", "warning", "error"]; + + const randomEvent = events[Math.floor(Math.random() * events.length)]; + const randomStatus = statuses[Math.floor(Math.random() * statuses.length)]; + + liveTable.addEvent(randomEvent, randomStatus); +}, 2000); +``` + +## Error Handling and Validation + +### Robust Table Creation + +```javascript +function createSafeTable(data, options = {}) { + try { + // Validate data + if (!Array.isArray(data) || data.length === 0) { + throw new Error("Data must be a non-empty array"); + } + + // Validate first row structure + const firstRow = data[0]; + if (typeof firstRow !== 'object' || firstRow === null) { + throw new Error("Each row must be an object"); + } + + // Create table with error handling + const table = new Table({ + ...options, + columns: options.columns || Object.keys(firstRow).map(key => ({ + name: key, + alignment: typeof firstRow[key] === 'number' ? 'right' : 'left' + })) + }); + + // Add rows with validation + data.forEach((row, index) => { + try { + // Validate row structure + if (typeof row !== 'object' || row === null) { + console.warn(`Skipping invalid row at index ${index}`); + return; + } + + table.addRow(row); + } catch (error) { + console.warn(`Error adding row ${index}:`, error.message); + } + }); + + return table; + + } catch (error) { + console.error("Failed to create table:", error.message); + return null; + } +} + +// Usage +const data = [ + { id: 1, name: "John", age: 25 }, + { id: 2, name: "Jane", age: 30 }, + null, // Invalid row + { id: 3, name: "Bob", age: 35 } +]; + +const table = createSafeTable(data, { + title: "User List", + style: "fatBorder" +}); + +if (table) { + table.printTable(); +} +``` \ No newline at end of file diff --git a/docs/api/configuration.md b/docs/api/configuration.md new file mode 100644 index 00000000..944e8a26 --- /dev/null +++ b/docs/api/configuration.md @@ -0,0 +1,594 @@ +--- +id: configuration +title: Configuration & Types +sidebar_label: Configuration +--- + +# Configuration & Types + +This section covers all configuration options, interfaces, and data types used throughout the library. + +## Configuration Interfaces + +### TableOptions + +Main configuration object for the Table constructor. + +```typescript +interface TableOptions { + // Column definitions + columns?: ColumnConfig[]; + + // Default options for all columns + defaultColumnOptions?: ColumnConfig; + + // Pre-defined rows + rows?: RowData[]; + + // Table styling + style?: TableStyle | CustomStyle; + + // Sorting function + sort?: (row1: RowData, row2: RowData) => number; + + // Filtering function + filter?: (row: RowData) => boolean; + + // Column visibility + enabledColumns?: string[]; + disabledColumns?: string[]; + + // Computed columns + computedColumns?: ComputedColumnConfig[]; + + // Table title + title?: string; + + // Custom color mapping + colorMap?: Record; +} +``` + +**Complete Example:** +```javascript +const table = new Table({ + // Column definitions + columns: [ + { name: "id", alignment: "left", color: "cyan" }, + { name: "name", alignment: "center", color: "yellow" }, + { name: "age", alignment: "right", color: "green" } + ], + + // Default options for any columns added later + defaultColumnOptions: { + alignment: "center", + color: "white", + maxLen: 20 + }, + + // Pre-populate with data + rows: [ + { id: 1, name: "John", age: 25 }, + { id: 2, name: "Jane", age: 30 } + ], + + // Table styling + style: "fatBorder", + title: "Employee Directory", + + // Sorting by age in descending order + sort: (row1, row2) => row2.age - row1.age, + + // Filter to show only adults + filter: (row) => row.age >= 18, + + // Computed columns + computedColumns: [ + { + name: "status", + function: (row) => row.age >= 25 ? "Senior" : "Junior" + } + ], + + // Show only specific columns + enabledColumns: ["id", "name", "age", "status"], + + // Custom colors + colorMap: { + custom_blue: '\x1b[34m', + custom_green: '\x1b[32m' + } +}); +``` + +### ColumnConfig + +Configuration for individual columns. + +```typescript +interface ColumnConfig { + // Required: Column identifier + name: string; + + // Optional: Display title (defaults to name) + title?: string; + + // Optional: Text alignment + alignment?: Alignment; + + // Optional: Text color + color?: Color; + + // Optional: Maximum length + maxLen?: number; + + // Optional: Minimum length + minLen?: number; +} +``` + +**Examples:** +```javascript +// Simple column +{ name: "id" } + +// Column with alignment +{ name: "name", alignment: "center" } + +// Column with color +{ name: "status", color: "red" } + +// Column with length constraints +{ name: "description", maxLen: 20, minLen: 10 } + +// Column with custom title +{ name: "created_at", title: "Created Date", alignment: "right" } + +// Complete configuration +{ + name: "salary", + title: "Annual Salary ($)", + alignment: "right", + color: "green", + maxLen: 15, + minLen: 10 +} +``` + +### RowOptions + +Options for row operations. + +```typescript +interface RowOptions { + // Row color + color?: Color; + + // Add separator after this row + separator?: boolean; +} +``` + +**Examples:** +```javascript +// Simple row +table.addRow({ id: 1, name: "John" }); + +// Row with color +table.addRow({ id: 1, name: "John" }, { color: "green" }); + +// Row with separator +table.addRow({ id: 1, name: "John" }, { separator: true }); + +// Row with both options +table.addRow( + { id: 1, name: "John" }, + { color: "red", separator: true } +); +``` + +### ComputedColumnConfig + +Configuration for computed columns. + +```typescript +interface ComputedColumnConfig { + // Required: Column name + name: string; + + // Required: Computation function + function: (row: RowData, index: number, array: RowData[]) => any; +} +``` + +**Examples:** +```javascript +// Simple computation +{ + name: "full_name", + function: (row) => `${row.first_name} ${row.last_name}` +} + +// Using row index +{ + name: "row_number", + function: (row, index) => index + 1 +} + +// Using all rows for comparison +{ + name: "percentile", + function: (row, index, array) => { + const sorted = array.sort((a, b) => a.score - b.score); + const position = sorted.findIndex(r => r.id === row.id); + return Math.round((position / array.length) * 100); + } +} + +// Complex computation with conditional logic +{ + name: "grade", + function: (row) => { + if (row.score >= 90) return "A"; + if (row.score >= 80) return "B"; + if (row.score >= 70) return "C"; + if (row.score >= 60) return "D"; + return "F"; + } +} +``` + +### CustomStyle + +Custom border style configuration. + +```typescript +interface CustomStyle { + headerTop: BorderLine; + headerBottom: BorderLine; + tableBottom: BorderLine; + vertical: string; +} + +interface BorderLine { + left: string; + mid: string; + right: string; + other: string; +} +``` + +**Example:** +```javascript +const customStyle = { + headerTop: { + left: "╔", + mid: "╦", + right: "╗", + other: "═" + }, + headerBottom: { + left: "╟", + mid: "╬", + right: "╢", + other: "═" + }, + tableBottom: { + left: "╚", + mid: "╩", + right: "╝", + other: "═" + }, + vertical: "║" +}; + +const table = new Table({ + style: customStyle, + columns: [ + { name: "id", alignment: "left" }, + { name: "name", alignment: "center" }, + { name: "age", alignment: "right" } + ] +}); +``` + +## Data Types + +### RowData + +Represents a single row of data. + +```typescript +type RowData = Record; +``` + +**Examples:** +```javascript +// Simple row +{ id: 1, name: "John", age: 25 } + +// Complex row with nested data +{ + id: 1, + name: "John Doe", + age: 25, + address: { + street: "123 Main St", + city: "New York" + }, + tags: ["developer", "senior"], + active: true +} + +// Row with computed values +{ + id: 1, + name: "John", + score: 85, + timestamp: new Date(), + metadata: { + created: "2024-01-01", + updated: "2024-01-15" + } +} +``` + +### Alignment + +Text alignment options. + +```typescript +type Alignment = "left" | "center" | "right"; +``` + +**Usage Examples:** +```javascript +// Left alignment (default) +{ name: "id", alignment: "left" } + +// Center alignment +{ name: "name", alignment: "center" } + +// Right alignment +{ name: "age", alignment: "right" } +``` + +### Color + +Available color options. + +```typescript +type Color = + | "red" + | "green" + | "yellow" + | "white" + | "blue" + | "magenta" + | "cyan" + | "white_bold" + | string; // Custom colors defined in colorMap +``` + +**Usage Examples:** +```javascript +// Built-in colors +{ name: "status", color: "red" } +{ name: "name", color: "green" } +{ name: "warning", color: "yellow" } + +// Custom colors +const table = new Table({ + colorMap: { + success: '\x1b[32m', + error: '\x1b[31m', + warning: '\x1b[33m', + info: '\x1b[36m' + } +}); + +// Use custom colors +{ name: "status", color: "success" } +{ name: "error", color: "error" } +``` + +### TableStyle + +Pre-defined table border styles. + +```typescript +type TableStyle = "fatBorder" | "thinBorder" | "noBorder"; +``` + +**Examples:** +```javascript +// Fat border (thick lines) +const table = new Table({ style: "fatBorder" }); + +// Thin border (thin lines) +const table = new Table({ style: "thinBorder" }); + +// No border +const table = new Table({ style: "noBorder" }); +``` + +## Function Signatures + +### Sort Function + +```typescript +type SortFunction = (row1: RowData, row2: RowData) => number; +``` + +**Parameters:** +- `row1: RowData` - First row for comparison +- `row2: RowData` - Second row for comparison + +**Returns:** `number` - Negative if row1 < row2, positive if row1 > row2, 0 if equal + +**Examples:** +```javascript +// Sort by numeric value in ascending order +sort: (row1, row2) => row1.age - row2.age + +// Sort by numeric value in descending order +sort: (row1, row2) => row2.score - row1.score + +// Sort by string alphabetically +sort: (row1, row2) => row1.name.localeCompare(row2.name) + +// Sort by multiple fields +sort: (row1, row2) => { + if (row1.department !== row2.department) { + return row1.department.localeCompare(row2.department); + } + return row1.name.localeCompare(row2.name); +} + +// Sort by date +sort: (row1, row2) => new Date(row1.created) - new Date(row2.created) +``` + +### Filter Function + +```typescript +type FilterFunction = (row: RowData) => boolean; +``` + +**Parameters:** +- `row: RowData` - Row data to evaluate + +**Returns:** `boolean` - `true` to include row, `false` to exclude + +**Examples:** +```javascript +// Filter by numeric value +filter: (row) => row.age >= 18 + +// Filter by string value +filter: (row) => row.status === "active" + +// Filter by multiple conditions +filter: (row) => row.age >= 18 && row.status === "active" + +// Filter by array inclusion +filter: (row) => row.tags.includes("senior") + +// Filter by date range +filter: (row) => { + const date = new Date(row.created); + const start = new Date("2024-01-01"); + const end = new Date("2024-12-31"); + return date >= start && date <= end; +} + +// Complex filter with nested properties +filter: (row) => { + return row.address?.city === "New York" && + row.metadata?.active === true; +} +``` + +### Computed Column Function + +```typescript +type ComputedFunction = (row: RowData, index: number, array: RowData[]) => any; +``` + +**Parameters:** +- `row: RowData` - Current row data +- `index: number` - Current row index (0-based) +- `array: RowData[]` - Array of all rows + +**Returns:** `any` - Computed value for the column + +**Examples:** +```javascript +// Simple computation using row data +function: (row) => row.price * row.quantity + +// Using row index +function: (row, index) => `Row ${index + 1}` + +// Using all rows for comparison +function: (row, index, array) => { + const avg = array.reduce((sum, r) => sum + r.score, 0) / array.length; + return row.score > avg ? "Above Average" : "Below Average"; +} + +// Complex computation with conditional logic +function: (row, index, array) => { + const total = array.reduce((sum, r) => sum + r.amount, 0); + const percentage = ((row.amount / total) * 100).toFixed(2); + return `${percentage}%`; +} + +// Using index for ranking +function: (row, index, array) => { + const sorted = [...array].sort((a, b) => b.score - a.score); + const rank = sorted.findIndex(r => r.id === row.id) + 1; + return rank; +} +``` + +## TypeScript Enums + +### ALIGNMENT + +```typescript +enum ALIGNMENT { + LEFT = "left", + CENTER = "center", + RIGHT = "right" +} +``` + +**Usage:** +```typescript +import { ALIGNMENT } from "console-table-printer"; + +const table = new Table({ + columns: [ + { name: "id", alignment: ALIGNMENT.LEFT }, + { name: "name", alignment: ALIGNMENT.CENTER }, + { name: "age", alignment: ALIGNMENT.RIGHT } + ] +}); +``` + +### COLOR + +```typescript +enum COLOR { + RED = "red", + GREEN = "green", + YELLOW = "yellow", + WHITE = "white", + BLUE = "blue", + MAGENTA = "magenta", + CYAN = "cyan", + WHITE_BOLD = "white_bold" +} +``` + +**Usage:** +```typescript +import { COLOR } from "console-table-printer"; + +const table = new Table({ + columns: [ + { name: "status", color: COLOR.RED }, + { name: "name", color: COLOR.GREEN }, + { name: "warning", color: COLOR.YELLOW } + ] +}); +``` + +## Configuration Best Practices + +1. **Column Definition:** Define columns in constructor for better performance +2. **Default Options:** Use `defaultColumnOptions` for consistent styling +3. **Computed Columns:** Keep computation functions simple and efficient +4. **Custom Colors:** Use descriptive names for custom colors +5. **Sorting/Filtering:** Apply filters before sorting for better performance +6. **Type Safety:** Use TypeScript interfaces for better development experience \ No newline at end of file diff --git a/docs/api/core-functions.md b/docs/api/core-functions.md new file mode 100644 index 00000000..646f9857 --- /dev/null +++ b/docs/api/core-functions.md @@ -0,0 +1,207 @@ +--- +id: core-functions +title: Core Functions +sidebar_label: Core Functions +--- + +# Core Functions + +This section covers the main functions for creating and printing tables. + +## printTable + +### `printTable(data: RowData[], options?: PrintTableOptions): void` + +Prints a table directly from an array of data objects without creating a Table instance. + +**Parameters:** +- `data: RowData[]` - Array of objects representing table rows +- `options?: PrintTableOptions` - Optional configuration for the table + +**Returns:** `void` + +**Example:** +```javascript +const { printTable } = require("console-table-printer"); + +const data = [ + { id: 1, name: "John", age: 25 }, + { id: 2, name: "Jane", age: 30 } +]; + +printTable(data); +``` + +**With Options:** +```javascript +const { printTable } = require("console-table-printer"); + +const data = [ + { id: 1, name: "John", age: 25, status: "active" }, + { id: 2, name: "Jane", age: 30, status: "inactive" } +]; + +printTable(data, { + columns: [ + { name: "id", alignment: "left" }, + { name: "name", alignment: "center" }, + { name: "age", alignment: "right" } + ], + enabledColumns: ["id", "name", "age"], // Hide status column + title: "User List" +}); +``` + +## Table Constructor + +### `new Table(options?: TableOptions)` + +Creates a new Table instance with optional configuration. + +**Parameters:** +- `options?: TableOptions` - Optional configuration object + +**Returns:** `Table` instance + +### Constructor Overloads + +#### 1. Empty Constructor +```javascript +const table = new Table(); +``` + +Creates a table with default settings. Columns will be automatically detected from the first row added. + +#### 2. Column Names Array +```javascript +const table = new Table(["id", "name", "age"]); +``` + +Creates a table with predefined column names. All columns will use default settings. + +#### 3. Configuration Object +```javascript +const table = new Table({ + columns: [ + { name: "id", alignment: "left", color: "red" }, + { name: "name", alignment: "center" }, + { name: "age", alignment: "right", color: "green" } + ], + style: "fatBorder", + title: "User Data", + sort: (row1, row2) => row1.id - row2.id, + filter: (row) => row.age >= 18 +}); +``` + +### TableOptions Interface + +```typescript +interface TableOptions { + // Column definitions + columns?: ColumnConfig[]; + + // Default options for all columns + defaultColumnOptions?: ColumnConfig; + + // Pre-defined rows + rows?: RowData[]; + + // Table styling + style?: TableStyle | CustomStyle; + + // Sorting function + sort?: (row1: RowData, row2: RowData) => number; + + // Filtering function + filter?: (row: RowData) => boolean; + + // Column visibility + enabledColumns?: string[]; + disabledColumns?: string[]; + + // Computed columns + computedColumns?: ComputedColumnConfig[]; + + // Table title + title?: string; + + // Custom color mapping + colorMap?: Record; +} +``` + +### Complete Example + +```javascript +const { Table } = require("console-table-printer"); + +// Create table with comprehensive configuration +const table = new Table({ + // Define columns with specific properties + columns: [ + { + name: "id", + title: "ID", + alignment: "left", + color: "cyan", + maxLen: 10 + }, + { + name: "name", + title: "Full Name", + alignment: "center", + color: "yellow", + minLen: 15 + }, + { + name: "age", + title: "Age", + alignment: "right", + color: "green" + } + ], + + // Default options for any columns added later + defaultColumnOptions: { + alignment: "center", + color: "white" + }, + + // Pre-populate with data + rows: [ + { id: 1, name: "John Doe", age: 25 }, + { id: 2, name: "Jane Smith", age: 30 } + ], + + // Table styling + style: "fatBorder", + title: "Employee Directory", + + // Sorting by age in descending order + sort: (row1, row2) => row2.age - row1.age, + + // Filter to show only adults + filter: (row) => row.age >= 18, + + // Computed columns + computedColumns: [ + { + name: "status", + function: (row) => row.age >= 25 ? "Senior" : "Junior" + } + ], + + // Custom colors + colorMap: { + custom_blue: '\x1b[34m', + custom_green: '\x1b[32m' + } +}); + +// Add more data +table.addRow({ id: 3, name: "Bob Wilson", age: 35 }); + +// Print the table +table.printTable(); +``` diff --git a/docs/api/table-methods.md b/docs/api/table-methods.md new file mode 100644 index 00000000..8ef1831b --- /dev/null +++ b/docs/api/table-methods.md @@ -0,0 +1,367 @@ +--- +id: table-methods +title: Table Instance Methods +sidebar_label: Table Methods +--- + +# Table Instance Methods + +This section covers all methods available on Table instances for manipulating data and structure. + +## Row Management Methods + +### addRow + +### `addRow(rowData: RowData, options?: RowOptions): Table` + +Adds a single row to the table. + +**Parameters:** +- `rowData: RowData` - Object containing row data +- `options?: RowOptions` - Optional row-specific options + +**Returns:** `Table` instance (for method chaining) + +**Example:** +```javascript +const table = new Table(); +table.addRow({ id: 1, name: "John", age: 25 }); +``` + +**With Options:** +```javascript +const table = new Table(); +table.addRow( + { id: 1, name: "John", age: 25 }, + { color: "green", separator: true } +); +``` + +**Chaining:** +```javascript +const table = new Table(); +table + .addRow({ id: 1, name: "John", age: 25 }, { color: "green" }) + .addRow({ id: 2, name: "Jane", age: 30 }, { color: "blue" }) + .addRow({ id: 3, name: "Bob", age: 35 }, { color: "red" }); +``` + +### addRows + +### `addRows(rowsData: RowData[], options?: RowOptions): Table` + +Adds multiple rows to the table. + +**Parameters:** +- `rowsData: RowData[]` - Array of objects containing row data +- `options?: RowOptions` - Optional options applied to all rows + +**Returns:** `Table` instance (for method chaining) + +**Example:** +```javascript +const table = new Table(); +table.addRows([ + { id: 1, name: "John", age: 25 }, + { id: 2, name: "Jane", age: 30 }, + { id: 3, name: "Bob", age: 35 } +]); +``` + +**With Options:** +```javascript +const table = new Table(); +table.addRows([ + { id: 1, name: "John", age: 25 }, + { id: 2, name: "Jane", age: 30 }, + { id: 3, name: "Bob", age: 35 } +], { color: "yellow" }); +``` + +**Mixed with Separators:** +```javascript +const table = new Table(); + +// Add first group +table.addRows([ + { category: "Fruits", item: "Apple", price: 1.0 }, + { category: "Fruits", item: "Banana", price: 0.5 } +]); + +// Add separator +table.addRow({ category: "Fruits", item: "Orange", price: 0.75 }, { separator: true }); + +// Add second group +table.addRows([ + { category: "Vegetables", item: "Carrot", price: 0.3 }, + { category: "Vegetables", item: "Potato", price: 0.4 } +]); +``` + +## Column Management Methods + +### addColumn + +### `addColumn(columnConfig: ColumnConfig): Table` + +Adds a single column to the table. + +**Parameters:** +- `columnConfig: ColumnConfig` - Column configuration object + +**Returns:** `Table` instance (for method chaining) + +**Example:** +```javascript +const table = new Table(); +table.addColumn({ + name: "age", + alignment: "right", + color: "yellow" +}); +``` + +**Complete Column Configuration:** +```javascript +const table = new Table(); +table.addColumn({ + name: "salary", + title: "Annual Salary", + alignment: "right", + color: "green", + maxLen: 15, + minLen: 10 +}); +``` + +### addColumns + +### `addColumns(columnsConfig: ColumnConfig[]): Table` + +Adds multiple columns to the table. + +**Parameters:** +- `columnsConfig: ColumnConfig[]` - Array of column configuration objects + +**Returns:** `Table` instance (for method chaining) + +**Example:** +```javascript +const table = new Table(); +table.addColumns([ + { name: "id", alignment: "left", color: "cyan" }, + { name: "name", alignment: "center", color: "yellow" }, + { name: "age", alignment: "right", color: "green" } +]); +``` + +**Mixed Column Types:** +```javascript +const table = new Table(); +table.addColumns([ + // Simple column + { name: "id" }, + + // Column with alignment + { name: "name", alignment: "center" }, + + // Column with color + { name: "status", color: "red" }, + + // Column with length constraints + { name: "description", maxLen: 20, minLen: 10 }, + + // Column with custom title + { name: "created_at", title: "Created Date", alignment: "right" } +]); +``` + +## Output Methods + +### printTable + +### `printTable(): void` + +Prints the table to the console. + +**Parameters:** None + +**Returns:** `void` + +**Example:** +```javascript +const table = new Table(); +table.addRow({ id: 1, name: "John" }); +table.printTable(); +``` + +**Complete Workflow:** +```javascript +const table = new Table({ + columns: [ + { name: "id", alignment: "left" }, + { name: "name", alignment: "center" }, + { name: "age", alignment: "right" } + ] +}); + +table.addRows([ + { id: 1, name: "John", age: 25 }, + { id: 2, name: "Jane", age: 30 }, + { id: 3, name: "Bob", age: 35 } +]); + +table.printTable(); +``` + +### render + +### `render(): string` + +Renders the table as a string without printing it. + +**Parameters:** None + +**Returns:** `string` - The formatted table as a string + +**Example:** +```javascript +const table = new Table(); +table.addRow({ id: 1, name: "John" }); +const tableString = table.render(); +console.log(tableString); +``` + +**Advanced Usage:** +```javascript +const table = new Table({ + title: "User Report", + style: "fatBorder" +}); + +table.addRows([ + { id: 1, name: "John", age: 25 }, + { id: 2, name: "Jane", age: 30 } +]); + +// Get the formatted string +const report = table.render(); + +// Save to file +const fs = require('fs'); +fs.writeFileSync('user-report.txt', report); + +// Send via email +sendEmail('admin@company.com', 'User Report', report); + +// Log to different console +console.error(report); +``` + +## Method Chaining Examples + +### Complete Table Building +```javascript +const table = new Table() + .addColumn({ name: "id", alignment: "left", color: "cyan" }) + .addColumn({ name: "name", alignment: "center", color: "yellow" }) + .addColumn({ name: "age", alignment: "right", color: "green" }) + .addRow({ id: 1, name: "John", age: 25 }, { color: "blue" }) + .addRow({ id: 2, name: "Jane", age: 30 }, { color: "red" }) + .addRow({ id: 3, name: "Bob", age: 35 }, { separator: true }) + .addRow({ id: 4, name: "Alice", age: 28 }) + .printTable(); +``` + +### Dynamic Table Building +```javascript +const table = new Table(); + +// Add columns dynamically +const columns = ["id", "name", "email", "role"]; +columns.forEach(col => { + table.addColumn({ + name: col, + alignment: col === "id" ? "left" : "center" + }); +}); + +// Add rows from API data +async function buildUserTable() { + const users = await fetchUsers(); + + users.forEach((user, index) => { + const options = {}; + + // Add color based on role + if (user.role === "admin") { + options.color = "red"; + } else if (user.role === "manager") { + options.color = "yellow"; + } + + // Add separator after every 5 users + if ((index + 1) % 5 === 0) { + options.separator = true; + } + + table.addRow(user, options); + }); + + table.printTable(); +} +``` + +## RowOptions Interface + +```typescript +interface RowOptions { + // Row color + color?: Color; + + // Add separator after this row + separator?: boolean; +} +``` + +## ColumnConfig Interface + +```typescript +interface ColumnConfig { + // Required: Column identifier + name: string; + + // Optional: Display title (defaults to name) + title?: string; + + // Optional: Text alignment + alignment?: Alignment; + + // Optional: Text color + color?: Color; + + // Optional: Maximum length + maxLen?: number; + + // Optional: Minimum length + minLen?: number; +} +``` + +## Performance Tips + +1. **Batch Operations:** Use `addRows()` instead of multiple `addRow()` calls for better performance +2. **Column Pre-definition:** Define columns in constructor when possible +3. **Method Chaining:** Chain methods to reduce variable assignments +4. **Render vs Print:** Use `render()` when you need the string output for further processing +5. **Memory Management:** For large datasets, consider filtering data before adding to table + +## Error Handling + +Methods handle various error scenarios: + +1. **Invalid Row Data:** Validates row object structure +2. **Missing Column Names:** Throws error for undefined columns +3. **Invalid Options:** Falls back to defaults for invalid options +4. **Empty Data:** Handles empty arrays and objects gracefully +5. **Type Mismatches:** Converts data types when possible \ No newline at end of file diff --git a/sidebars.js b/sidebars.js index 619b5b61..f017fa0c 100644 --- a/sidebars.js +++ b/sidebars.js @@ -24,5 +24,11 @@ module.exports = { "doc-cli-install-quick-start", "doc-cli-brew" ], + "API Reference": [ + "api/core-functions", + "api/table-methods", + "api/configuration", + "api/advanced-features", + ], }, };