import Papa from 'papaparse'
import escapeHTML from 'lodash/escape'
const safeParse = d => {
try {
return JSON.parse(d)
} catch (err) {
return d
}
}
export function renderCSVPreview (csv, options = {}, attr = '') {
const opt = Object.keys(options).reduce((acc, key) => {
return Object.assign(acc, {
[key]: safeParse(options[key])
})
}, {})
const results = Papa.parse(csv.trim(), opt)
if (opt.header) {
const fields = results.meta.fields
return `
${fields.map(f => `${escapeHTML(f)} | `).join('')}
${results.data.map(d => `
${fields.map(f => `${escapeHTML(d[f])} | `).join('')}
`).join('')}
`
} else {
return `
${results.data.map(d => `
${d.map(f => `${escapeHTML(f)} | `).join('')}
`).join('')}
`
}
}