|
| 1 | + |
| 2 | +/** |
| 3 | + * Convert an array of objects to a markdown table string. |
| 4 | + * Truncates cell values to maxChars, appending '…' if truncated. |
| 5 | + * Marks columns as "(truncated)" in the header if any cell was truncated. |
| 6 | + * @param {Record<string, any>[]} data |
| 7 | + * @param {number} maxChars |
| 8 | + * @returns {string} |
| 9 | + */ |
| 10 | +export function markdownTable(data, maxChars) { |
| 11 | + if (data.length === 0) { |
| 12 | + return '(empty table)' |
| 13 | + } |
| 14 | + const columns = Object.keys(data[0] ?? {}) |
| 15 | + const truncated = columns.map(() => false) // is column truncated? |
| 16 | + /** @type {string[]} */ |
| 17 | + const rows = [] |
| 18 | + for (const row of data) { |
| 19 | + const rowStrings = new Array(columns.length) |
| 20 | + for (let i = 0; i < columns.length; i++) { |
| 21 | + const column = columns[i] |
| 22 | + const value = column && row[column] |
| 23 | + if (value === null || value === undefined) { |
| 24 | + rowStrings[i] = '' |
| 25 | + } else if (typeof value === 'object') { |
| 26 | + const { json, isTruncated } = jsonStringify(value, maxChars) |
| 27 | + if (isTruncated) truncated[i] = true |
| 28 | + rowStrings[i] = json.replace(/\|/g, '\\|') // Escape pipe characters |
| 29 | + } else { |
| 30 | + let str = String(value) |
| 31 | + if (str.length > maxChars) { |
| 32 | + str = str.slice(0, maxChars) + '…' |
| 33 | + truncated[i] = true |
| 34 | + } |
| 35 | + rowStrings[i] = str.replace(/\|/g, '\\|') // Escape pipe characters |
| 36 | + } |
| 37 | + } |
| 38 | + rows.push(`| ${rowStrings.join(' | ')} |`) |
| 39 | + } |
| 40 | + // Show which columns were truncated in the header |
| 41 | + const columnsWithTruncation = columns |
| 42 | + .map((col, idx) => truncated[idx] ? `${col} (truncated)` : col) |
| 43 | + const header = `| ${columnsWithTruncation.join(' | ')} |` |
| 44 | + const separator = `| ${columns.map(() => '---').join(' | ')} |` |
| 45 | + |
| 46 | + return [header, separator, ...rows].join('\n') |
| 47 | +} |
| 48 | + |
| 49 | +/** |
| 50 | + * JSON stringify with truncation. |
| 51 | + * @param {unknown} obj |
| 52 | + * @param {number} maxChars |
| 53 | + * @returns {{json: string, isTruncated: boolean}} |
| 54 | + */ |
| 55 | +function jsonStringify(obj, maxChars) { |
| 56 | + const fullJson = JSON.stringify(obj) |
| 57 | + if (fullJson.length <= maxChars) { |
| 58 | + return { json: fullJson, isTruncated: false } |
| 59 | + } |
| 60 | + const sliced = fullJson.slice(0, maxChars) + '…' |
| 61 | + return { json: sliced, isTruncated: true } |
| 62 | +} |
0 commit comments