Skip to content

Instantly share code, notes, and snippets.

@Nephos
Last active July 10, 2018 10:08
Show Gist options
  • Save Nephos/61470cb2ae6fa2b19fe0a2e36ce2afcf to your computer and use it in GitHub Desktop.
Save Nephos/61470cb2ae6fa2b19fe0a2e36ce2afcf to your computer and use it in GitHub Desktop.
Number.prototype.times = function (callback) {
const collect = [];
for (let i = 0; i < this; i++) {
collect.push(callback(i, this));
}
return collect;
}
function htmlizeLeef(data, parent) {
const indent = (data.level - 1).times(i => "&nbsp;&nbsp;").join('');
return `<tr><th align=\"left\">${indent}${data.key}</th><td align=\"right\">${data.value}</td>`;
}
function buildHtmlObject(empty, header) {
if (empty) return { top: '', bottom: '' };
const top = "<table>\n" + (header ? "<tr><th align=\"left\">key</th><th align=\"right\">value</th></tr>\n" : "");
const bottom = "</table>\n";
return { top, bottom };
}
function htmlize(json, key = '', level = 0, parent = undefined) {
if (typeof json === 'object') {
const { top, bottom } = buildHtmlObject(level > 0, level === 0);
const object_content = Object.keys(json).map(key => {
const subbuild = htmlize(json[key], key, level + 1, json);
return subbuild;
});
const object_head = htmlizeLeef({ level: level, key: key, value: object_content.join("\n") }, parent);
return top + object_head + bottom;
}
else {
const { top, bottom } = buildHtmlObject(level > 0, level === 0);
return top + htmlizeLeef({ level: level, key: key, value: JSON.stringify(json) }, parent) + bottom;
}
}
module.exports = {
htmlize,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment