|
| 1 | +--- |
| 2 | +id: doc-transform |
| 3 | +title: Transform Functions |
| 4 | +sidebar_label: Transform Functions |
| 5 | +--- |
| 6 | + |
| 7 | +import useBaseUrl from '@docusaurus/useBaseUrl'; |
| 8 | + |
| 9 | +Transform functions allow you to format cell values before display without modifying the original data. This is useful for currency formatting, date conversion, string manipulation, and any other display transformations. |
| 10 | + |
| 11 | +## Basic String Transform |
| 12 | + |
| 13 | +```javascript |
| 14 | +import { Table } from 'console-table-printer'; |
| 15 | + |
| 16 | +const p = new Table({ |
| 17 | + columns: [ |
| 18 | + { name: 'original', alignment: 'left' }, |
| 19 | + { |
| 20 | + name: 'uppercase', |
| 21 | + alignment: 'left', |
| 22 | + // highlight-next-line |
| 23 | + transform: (value) => String(value).toUpperCase() |
| 24 | + }, |
| 25 | + ], |
| 26 | +}); |
| 27 | + |
| 28 | +p.addRow({ original: 'hello', uppercase: 'hello' }); |
| 29 | +p.addRow({ original: 'world', uppercase: 'world' }); |
| 30 | +p.addRow({ original: 'test', uppercase: 'test' }); |
| 31 | + |
| 32 | +p.printTable(); |
| 33 | +``` |
| 34 | + |
| 35 | +The `uppercase` column displays the transformed values while the original data remains unchanged. |
| 36 | + |
| 37 | +## Currency Formatting |
| 38 | + |
| 39 | +One of the most common use cases is formatting numbers as currency: |
| 40 | + |
| 41 | +```javascript |
| 42 | +import { Table } from 'console-table-printer'; |
| 43 | + |
| 44 | +const p = new Table({ |
| 45 | + columns: [ |
| 46 | + { name: 'item', alignment: 'left' }, |
| 47 | + { |
| 48 | + name: 'price', |
| 49 | + alignment: 'right', |
| 50 | + // highlight-next-line |
| 51 | + transform: (value) => `$${Number(value).toFixed(2)}` |
| 52 | + }, |
| 53 | + ], |
| 54 | +}); |
| 55 | + |
| 56 | +p.addRows([ |
| 57 | + { item: 'Coffee', price: 3.5 }, |
| 58 | + { item: 'Sandwich', price: 7.99 }, |
| 59 | + { item: 'Water', price: 1 }, |
| 60 | +]); |
| 61 | + |
| 62 | +p.printTable(); |
| 63 | +``` |
| 64 | + |
| 65 | +This transforms raw numbers like `3.5` into formatted currency like `$3.50`. |
0 commit comments