Skip to content

Instantly share code, notes, and snippets.

@westc
Last active April 25, 2023 02:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/9317635df491f8e9d256c57f3fcd2f4e to your computer and use it in GitHub Desktop.
Save westc/9317635df491f8e9d256c57f3fcd2f4e to your computer and use it in GitHub Desktop.
Converts an array of arrays of values to a CSV string.
/**
* @preserve Copyright (c) 2019 Christopher West
* Licensed under the MIT license.
*/
/**
* Converts an array of arrays of values to a CSV string.
* @param {any[][]} rows
* An array of arrays of values that should be converted to a CSV string.
* @param {Object} opt_options
* @param {string=} opt_options.nullString
* This value will be used as the string that will appear whenever `null` or
* `undefined` is found (as long as `valueOf()` isn't defined).
* @param {string[]=} opt_options.headers
* Optional array of headers that will appear on the first row.
* @param {((value: any, row: number, col: number, rows) => any)=} opt_options.valueOf
* Optional function run for each cell value in rows to get the value that
* will be shown in the output CSV code.
* @returns {string}
* The CSV version of `rows` with any specified options.
*/
function toCSV(rows, opt_options) {
let {headers, nullString, valueOf} = Object(opt_options);
if (headers) {
rows = [headers].concat(rows);
}
if (nullString == null) nullString = '(NULL)';
return rows
.map(function (row, rowIndex) {
return row.map(function (cell, colIndex) {
if (valueOf && (!headers || rowIndex)) {
cell = valueOf.call(opt_options, cell, rowIndex, colIndex, rows);
}
cell = cell != null
? 'string' === typeof cell
? cell
: 'function' === typeof cell.toString
? cell + ""
: Object.prototype.toString.call(cell)
: nullString;
return /[",\n\r]/.test(cell) ? '"' + (cell).replace(/"/g, '""') + '"' : cell;
}).join(',');
})
.join('\n');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment