UNPKG

uno-js

Version:

JS/TS common used functions, zero dependencies

32 lines (31 loc) 1.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createCsvData = void 0; const escapeValuesWithQuotes = (str) => str.match(/\$-?(\d{1,3},+)?(\d{1,3},\d{3}(\.\d)*)/g) ? str.replace(/,\$/g, '","$') : str.replace(/,/g, '","'); const wrapWithQuotes = (text) => (typeof text === 'string' ? `"${text.replace(/"/g, '""')}"` : `"${text}"`); const formatMixedEntry = (arr) => arr.constructor === Array ? arr.map(wrapWithQuotes).join() : wrapWithQuotes(arr); const formatEntryWithCommas = (textString, text) => (textString.match(/(,\s)+/g) || []).length === 0 ? wrapWithQuotes(escapeValuesWithQuotes(textString)) : formatMixedEntry(text); const escapeValuesWithCommas = (data) => data.map((value) => [...value] .map((text) => { const textString = !text ? 'N/A' : String(text); return textString.includes(',') ? formatEntryWithCommas(textString, text) : wrapWithQuotes(textString); }) .join(',')); const createCsvData = (csv, headers) => [headers.join(','), ...escapeValuesWithCommas(csv)].join('\r\n'); exports.createCsvData = createCsvData; exports.default = (csv, headers, fileName) => { const dataWithBom = `\uFEFF${(0, exports.createCsvData)(csv, headers)}`; const blob = new Blob([dataWithBom], { type: 'text/csv;charset=utf-8;' }); const link = document.createElement('a'); if (link.download !== undefined) { const url = URL.createObjectURL(blob); link.setAttribute('href', url); link.setAttribute('download', fileName); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } };