From 73a35d4e0a62d9bbad7f48d8cd0a66ef5030e110 Mon Sep 17 00:00:00 2001 From: susmitapiya <susmitaduttapiya@gmail.com> Date: Mon, 20 Apr 2020 21:32:14 +0300 Subject: [PATCH] function javascript file --- functions.js | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 functions.js diff --git a/functions.js b/functions.js new file mode 100644 index 0000000..1d21e57 --- /dev/null +++ b/functions.js @@ -0,0 +1,56 @@ +/** + * Make a table representation of the data + * + * @param {Array[Array[*]]} data The data to represent in the table, a 2D array + * @param {Array[String]} headerRowTexts The strings to show in the header row of the table. + * If null, no header row is created. + */ +function makeTable(data, headerRowTexts = null) { + let table = document.createElement('table'); + + let thead = document.createElement('thead'); + table.append(thead); + // Construct the header row + if (headerRowTexts != null) { // Construct header row + let header = document.createElement('tr'); + for(let s of headerRowTexts) { + let thElem = document.createElement('th'); + thElem.textContent = s; + header.append(thElem); + } + thead.append(header); + } + + // Construct the non-header rows + let tbody = document.createElement('tbody'); + for (let row of data) { + let trElem = document.createElement('tr'); + for (let value of row) { + let tdElem = document.createElement('td'); + tdElem.textContent = value; + trElem.append(tdElem); + } + tbody.append(trElem); + } + table.append(tbody); + return table; +} + +/** + * Make a table representation of the array of objects. Note: this function + * can generate an acceptable-looking output table only if the objects of + * objArr are simple enough. For instance, nested objects may lead to table + * cells with too much contents or to cells of the form [object Object] if + * string conversion methods have not been defined for those inner objects. + * + * @param {Array[Object]} objArr + */ +function objectsAsTable(objArr) { + if (objArr.length == 0) { + return makeTable([], null); + } + firstObj = objArr[0]; + let header = Object.keys(firstObj); + let arr = objArr.map(e => Object.values(e)); + return makeTable(arr, header); +} \ No newline at end of file -- GitLab