{"id":5404,"date":"2021-09-28T15:50:53","date_gmt":"2021-09-28T14:50:53","guid":{"rendered":"https:\/\/solidt.eu\/site\/?p=5404"},"modified":"2022-07-25T08:35:41","modified_gmt":"2022-07-25T07:35:41","slug":"javascript-printtable","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/javascript-printtable\/","title":{"rendered":"Javascript PrintTable"},"content":{"rendered":"\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"javascript\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">(() => {\n    const repeat = (char, length) => Array(length + 1).join(char);\n    const ljust = (s, width, c = \" \") => s.length &lt; width ? s + repeat(c.slice(0, 1), width - s.length) : s; \/\/ padleft\n    const rjust = (s, width, c = \" \") => s.length &lt; width ? repeat(c.slice(0, 1), width - s.length) + s : s; \/\/ padright\n    function center(s, width, c = \" \") { \/\/ padcenter\n        if (s.length &lt; width) {\n            c = c.slice(0, 1);\n            const len = width - s.length;\n            const remain = (len % 2 === 0) ? \"\" : c;\n            const pads = repeat(c, Math.floor(len \/ 2));\n            return pads + s + pads + remain;\n        } else\n            return s;\n    }\n    const ALIGN = {\n        LEFT: 0,\n        CENTER: 1,\n        RIGHT: 2\n    };\n    const printTable = (data) => {\n        if (!Array.isArray(data)) return;\n        if (data.length &lt; 1) return new Error(\"Table should contain at least 1 row\");\n        const columns = [];\n        const typeRow = data[1];\n        const columnCount = typeRow.length;\n        for (let c = 0; c &lt; columnCount; c++) {\n            const column = {\n                index: c,\n                name: `Col ${c}`,\n                size: 0,\n                align: ALIGN.LEFT\n            };\n            const type = typeof typeRow[c];\n            if (type === \"number\") {\n                column.align = ALIGN.RIGHT;\n            }\n            column.size = data.reduce((v, r) => Math.max(v, String(r[c]).length), 0);\n            columns.push(column);\n        }\n        const tabledata = [];\n        for (const row of data) {\n            const rowdata = [];\n            for (const col of columns) {\n                const value = String(row[col.index]);\n                if (col.align == ALIGN.CENTER) {\n                    rowdata.push(center(value, col.size))\n                } else  if (col.align == ALIGN.RIGHT) {\n                    rowdata.push(rjust(value, col.size))\n                } else {\n                    rowdata.push(ljust(value, col.size));\n                }\n            }\n            tabledata.push(`| ${rowdata.join(\" | \")} |`);\n        }\n        const width = tabledata[0].length;\n        const line = repeat(\"=\", width);\n        tabledata.splice(1, 0, line);\n        tabledata.unshift(line);\n        tabledata.push(line);\n        return tabledata.join(\"\\n\");\n    }\n\n    const objsToTable = (data) => {\n        const result = [];\n        const columns = Object.keys(data[0]);\n        let row = [];\n        for (const c of columns) {\n            row.push(c);\n        }\n        result.push(row);\n        for (const item of data) {\n            row = [];\n            for (const c of columns) {\n                row.push(item[c]);\n            }\n            result.push(row);\n        }\n        return result;\n    };\n\n    const data = [\n        {\"id\":1,\"first_name\":\"Hogan\",\"last_name\":\"Egdal\",\"age\":55,\"email\":\"hegdal0@t-online.de\",\"gender\":\"Female\",\"ip_address\":\"246.182.212.226\"},\n        {\"id\":2,\"first_name\":\"Haily\",\"last_name\":\"Cheales\",\"age\":56,\"email\":\"hcheales1@mlb.com\",\"gender\":\"Female\",\"ip_address\":\"89.149.57.20\"},\n        {\"id\":3,\"first_name\":\"Mandel\",\"last_name\":\"Calken\",\"age\":39,\"email\":\"mcalken2@mozilla.com\",\"gender\":\"Genderfluid\",\"ip_address\":\"146.82.130.243\"},\n        {\"id\":4,\"first_name\":\"Meade\",\"last_name\":\"Ongin\",\"age\":12,\"email\":\"mongin3@technorati.com\",\"gender\":\"Genderfluid\",\"ip_address\":\"85.33.52.45\"},\n        {\"id\":5,\"first_name\":\"Jeannie\",\"last_name\":\"Balazs\",\"age\":22,\"email\":\"jbalazs4@tripod.com\",\"gender\":\"Bigender\",\"ip_address\":\"124.200.22.70\"},\n        {\"id\":6,\"first_name\":\"Leonie\",\"last_name\":\"Mimmack\",\"age\":29,\"email\":\"lmimmack5@chron.com\",\"gender\":\"Genderfluid\",\"ip_address\":\"140.108.128.252\"},\n        {\"id\":7,\"first_name\":\"Inglis\",\"last_name\":\"Daspar\",\"age\":80,\"email\":\"idaspar6@odnoklassniki.ru\",\"gender\":\"Agender\",\"ip_address\":\"172.50.192.149\"},\n        {\"id\":8,\"first_name\":\"Michal\",\"last_name\":\"Itzik\",\"age\":41,\"email\":\"mitzik7@pcworld.com\",\"gender\":\"Genderqueer\",\"ip_address\":\"164.224.49.132\"},\n        {\"id\":9,\"first_name\":\"Vikki\",\"last_name\":\"Edelheit\",\"age\":20,\"email\":\"vedelheit8@dagondesign.com\",\"gender\":\"Polygender\",\"ip_address\":\"112.172.252.190\"},\n        {\"id\":10,\"first_name\":\"Mallory\",\"last_name\":\"Stamp\",\"age\":66,\"email\":\"mstamp9@cnn.com\",\"gender\":\"Genderfluid\",\"ip_address\":\"51.223.32.46\"}\n    ];\n\n    const out = printTable(objsToTable(data));\n    console.log(out);\n})();<\/pre><\/div>\n\n\n\n<p>Result<\/p>\n\n\n\n<div style=\"height: 250px; position:relative; margin-bottom: 50px;\" class=\"wp-block-simple-code-block-ace\"><pre class=\"wp-block-simple-code-block-ace\" style=\"position:absolute;top:0;right:0;bottom:0;left:0\" data-mode=\"javascript\" data-theme=\"monokai\" data-fontsize=\"14\" data-lines=\"Infinity\" data-showlines=\"true\" data-copy=\"false\">==================================================================================================\n| id | first_name | last_name | age | email                      | gender      | ip_address      |\n==================================================================================================\n|  1 | Hogan      | Egdal     |  55 | hegdal0@t-online.de        | Female      | 246.182.212.226 |\n|  2 | Haily      | Cheales   |  56 | hcheales1@mlb.com          | Female      | 89.149.57.20    |\n|  3 | Mandel     | Calken    |  39 | mcalken2@mozilla.com       | Genderfluid | 146.82.130.243  |\n|  4 | Meade      | Ongin     |  12 | mongin3@technorati.com     | Genderfluid | 85.33.52.45     |\n|  5 | Jeannie    | Balazs    |  22 | jbalazs4@tripod.com        | Bigender    | 124.200.22.70   |\n|  6 | Leonie     | Mimmack   |  29 | lmimmack5@chron.com        | Genderfluid | 140.108.128.252 |\n|  7 | Inglis     | Daspar    |  80 | idaspar6@odnoklassniki.ru  | Agender     | 172.50.192.149  |\n|  8 | Michal     | Itzik     |  41 | mitzik7@pcworld.com        | Genderqueer | 164.224.49.132  |\n|  9 | Vikki      | Edelheit  |  20 | vedelheit8@dagondesign.com | Polygender  | 112.172.252.190 |\n| 10 | Mallory    | Stamp     |  66 | mstamp9@cnn.com            | Genderfluid | 51.223.32.46    |\n==================================================================================================<\/pre><\/div>\n","protected":false},"excerpt":{"rendered":"<p>Result<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[5,4,1],"tags":[],"class_list":["post-5404","post","type-post","status-publish","format-standard","hentry","category-javascript","category-programming","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/5404","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=5404"}],"version-history":[{"count":12,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/5404\/revisions"}],"predecessor-version":[{"id":5465,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/5404\/revisions\/5465"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=5404"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=5404"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=5404"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}