SHARE
TWEET

Untitled

a guest Apr 21st, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const csvEscape = function() {
  2.   const map = {
  3.     ";": ",",
  4.     "\n": "\\n"
  5.   };
  6.   const replacerRe = /./gsm;
  7.   const replacer = x => `\\x${x.charCodeAt(0).toString(16).padStart(2, 0)}`;
  8.   const escaped = Object.keys(map).map(x => x.replace(replacerRe, replacer));
  9.   const escapeRe = new RegExp(escaped.join("|"), "g");
  10.   const escape = x => map[x];
  11.   return el => {
  12.     const span = el.getAttribute("colspan") | 0;
  13.     const escaped = el.textContent.trim().replace(escapeRe, escape);
  14.     return span < 2 ? escaped : Array(span).fill(escaped).join(";");
  15.   };
  16. }();
  17.  
  18. function processRow({ children: row }) {
  19.   const length = row.length;
  20.   if (!length) return "";
  21.   const str = length > 50 ? Array(length) : [];
  22.   str[0] = csvEscape(row[0]);
  23.   for (let i = 1; i < length; ++i) {
  24.     str[i] = `;${csvEscape(row[i])}`;
  25.   }
  26.   return str.join("");
  27. }
  28.  
  29. function processHead(table, target) {
  30.   const { tHead } = table;
  31.   if (!tHead) return;
  32.   const { rows } = tHead;
  33.   switch (rows.length) {
  34.     case 0: return;
  35.     case 1: break;
  36.     default: throw new RangeError("can't have more than one head row");
  37.   }
  38.   target.push(processRow(rows[0]));
  39. }
  40.  
  41. function processBodies(table, target) {
  42.   for (const body of table.tBodies) {
  43.     for (const row of body.children) {
  44.       if (row.tagName === "TR") {
  45.         target.push(processRow(row));
  46.       }
  47.     }
  48.   }
  49. }
  50.  
  51. function processFoot(table, target) {
  52.   const { tFoot } = table;
  53.   if (!tFoot) return;
  54.   for (const row of tFoot.rows) {
  55.     target.push(processRow(row));
  56.   }
  57. }
  58.  
  59. export default function tableToCsv(table) {
  60.   if (table == null || table.tagName !== "TABLE") {
  61.     throw new TypeError("invalid argument");
  62.   }
  63.   const result = [];
  64.   processHead(table, result);
  65.   processBodies(table, result);
  66.   processFoot(table, result);
  67.   return result.join("\n");
  68. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top