function escapeCSV(val) {
  if (val == null) return ''
  var s = String(val)
  if (s.indexOf(',') > -1 || s.indexOf('"') > -1 || s.indexOf('\n') > -1) {
    return '"' + s.replace(/"/g, '""') + '"'
  }
  return s
}

function exportCSV(filename, headers, rows) {
  var lines = [headers.map(escapeCSV).join(',')]
  for (var i = 0; i < rows.length; i++) {
    lines.push(rows[i].map(escapeCSV).join(','))
  }
  var csv = '\uFEFF' + lines.join('\n')
  var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  var url = URL.createObjectURL(blob)
  var a = document.createElement('a')
  a.href = url
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)
}

export { exportCSV }
