Last active
June 27, 2022 06:40
-
-
Save Cicolas/7d80199528914b1594e4e5cfd2ccbf42 to your computer and use it in GitHub Desktop.
A utility code to convert yours objects into a html visualization.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Nícolas Carvalho | |
* Maringá, PR - Brasil | |
* 27/06/2022 | |
* | |
* A utility code to convert yours objects into a html visualization. (Based on JSON.Stringfy()) | |
* | |
* https://github.com/Cicolas | |
*/ | |
/** | |
* transform the given object in a html view of it | |
* @param obj the object | |
* @param indent the inital indent level | |
* @returns a HTML string | |
*/ | |
export default function htmlfy(obj: any, indent: number = 0): string { | |
const isObject = (obj: any): obj is object => typeof obj === "object"; | |
if (isObject(obj) && obj) return `${objectStringfy(obj, indent)}`; | |
let str = '<span class='; | |
switch(typeof obj) { | |
case "string": | |
str += `"green">"${obj}"`; | |
break; | |
case "bigint": | |
str += `"blue">BigInt(${obj})`; | |
break; | |
case "number": | |
str += `"blue">${obj}`; | |
break; | |
case "boolean": | |
str += `"yellow">${obj}`; | |
break; | |
case "undefined": | |
str += `"grey i">${obj}`; | |
break; | |
case "symbol": | |
str += `"purple">${obj.toString()}`; | |
break; | |
case "function": | |
str += `"b i">${obj}`; | |
break; | |
case "object": | |
str += `"black">${obj}`; | |
break; | |
default: | |
throw `type ${typeof obj} not suported by htmlfy`; | |
} | |
return str + '</span>'; | |
} | |
function objectStringfy(obj: object, indentation: number): string { | |
const getIndentation = () => "    ".repeat(indentation); | |
const className = obj.constructor.name; | |
const keys = Object.keys(obj); | |
let str = ` | |
<span class="b i">(${className})</span> <br> | |
${getIndentation()}{ <br> | |
`; | |
indentation++; | |
const empty = getIndentation() + '<span class="grey i"><Empty></span>'; | |
str += keys.length > 0 ? keys.map((k, i) => { | |
return `${getIndentation()}<span class="grey">${k}</span>: ${htmlfy( | |
obj[k], | |
indentation | |
)}`; | |
}).join(",<br>"): empty; | |
indentation--; | |
str += `<br>${getIndentation()}}`; | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment