( data: readonly DataItem[], options?: StringifyOptions, )
| 426 | * @returns A CSV string. |
| 427 | */ |
| 428 | export function stringify( |
| 429 | data: readonly DataItem[], |
| 430 | options?: StringifyOptions, |
| 431 | ): string { |
| 432 | const { headers = true, separator: sep = ",", columns = [], bom = false } = |
| 433 | options ?? {}; |
| 434 | |
| 435 | if (sep.includes(QUOTE) || sep.includes(CRLF)) { |
| 436 | const message = [ |
| 437 | "Separator cannot include the following strings:", |
| 438 | ' - U+0022: Quotation mark (")', |
| 439 | " - U+000D U+000A: Carriage Return + Line Feed (\\r\\n)", |
| 440 | ].join("\n"); |
| 441 | throw new TypeError(message); |
| 442 | } |
| 443 | |
| 444 | const normalizedColumns = columns.map(normalizeColumn); |
| 445 | let output = ""; |
| 446 | |
| 447 | if (bom) { |
| 448 | output += BYTE_ORDER_MARK; |
| 449 | } |
| 450 | |
| 451 | if (headers && normalizedColumns.length > 0) { |
| 452 | output += normalizedColumns |
| 453 | .map((column) => getEscapedString(column.header, sep)) |
| 454 | .join(sep); |
| 455 | output += CRLF; |
| 456 | } |
| 457 | |
| 458 | for (const item of data) { |
| 459 | const values = getValuesFromItem(item, normalizedColumns); |
| 460 | output += values |
| 461 | .map((value) => getEscapedString(value, sep)) |
| 462 | .join(sep); |
| 463 | output += CRLF; |
| 464 | } |
| 465 | |
| 466 | return output; |
| 467 | } |
no test coverage detected