UNPKG

@beenotung/tslib

Version:
105 lines (104 loc) 3.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.dateFormatter = void 0; exports.setDateFormatter = setDateFormatter; exports.resetDateFormatter = resetDateFormatter; exports.setDateFormatLocale = setDateFormatLocale; exports.resetDateFormatLocale = resetDateFormatLocale; exports.toString = toString; exports.displayJSON = displayJSON; exports.csv_to_table_html = csv_to_table_html; let dateFormatter = (x) => x.toString(); exports.dateFormatter = dateFormatter; function setDateFormatter(f) { exports.dateFormatter = f; } function resetDateFormatter() { exports.dateFormatter = (x) => x.toString(); } function setDateFormatLocale(lang, timezone) { exports.dateFormatter = x => x.toLocaleString(lang, { timeZone: timezone }); } function resetDateFormatLocale() { exports.dateFormatter = x => x.toLocaleString(); } function toString(o) { switch (typeof o) { case 'string': return o; } if (o instanceof Date) { return (0, exports.dateFormatter)(o); } if (o instanceof Set) { return toString(Array.from(o)); } return JSON.stringify(o, undefined, 2); } const escape_space = '&nbsp;'; function displayJSON(o, mode = 'table') { if (mode === 'raw') { return `<pre>${toString(o)}</pre>`; } /* mode === 'table' */ switch (typeof o) { case 'object': if (Array.isArray(o)) { return ('<ol>' + o .map(x => '<li>' + displayJSON(x, mode) + '</li>') .join('') + '</ol>'); } if (o instanceof Set) { o = Array.from(o); return ('<ul>' + o .map(x => '<li>' + displayJSON(x, mode) + '</li>') .join('') + '</ul>'); } if (o instanceof Date) { return toString(o); } if (o === null) { return 'null'; } break; case 'string': { const s = o; return s .split('\r') .join('') .split('\n') .join('<br>') .split(' ') .join(escape_space.repeat(2)) .split('\t') .join(escape_space.repeat(4)); } case 'number': return o.toString(); default: return `<pre>${JSON.stringify(o)}</pre>`; } /* being object */ const rows = Object.keys(o) .map(k => { const v = o[k]; return `<tr><td>${displayJSON(k, mode)}</td><td>${displayJSON(v, mode)}</td></tr>`; }) .join(''); return `<table><tbody>${rows}</tbody></table>`; } function mkHtmlText(tagName, content) { return `<${tagName}>${content}</${tagName}>`; } function csv_to_table_html(rows) { const thead = mkHtmlText('thead', mkHtmlText('tr', rows[0].map(col => mkHtmlText('th', col)).join(''))); const tbody = mkHtmlText('tbody', rows .slice(1) .map(cols => mkHtmlText('tr', cols.map(col => mkHtmlText('td', col)).join(''))) .join('')); return mkHtmlText('table', thead + tbody); }