Created
April 14, 2022 00:59
-
-
Save aleclarson/c093c9dd8cba598a44a2cf6a4e5d8764 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const reservedChars = /[\r\n,"]/ | |
module.exports = function toCSV(header, rows) { | |
rows = rows.map(row => row.map(valueToString).join(',')) | |
return [header.join(','), ...rows].join('\r\n') + '\r\n' | |
} | |
function valueToString(value) { | |
return value === undefined | |
? '' | |
: (typeof value === 'string' && reservedChars.test(value)) || | |
(typeof value === 'object' && value !== null) | |
? escapeString(value) | |
: value | |
} | |
function escapeString(value) { | |
let str = JSON.stringify(value) | |
if (typeof value === 'string') { | |
str = str.slice(1, -1) | |
} | |
str = str.replace(/"/g, '""') | |
return '"' + str + '"' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment