JSFiddle - React, Tailwind, and code Playground
by mihaibirsan
HTML
<pre id="results"></pre>
<table id="results-table">
<thead></thead>
<tbody></tbody>
</table>
JavaScript
const batch = [
"",
"foo",
undefined,
null,
0,
1,
Infinity,
NaN
];
const approaches = {
nonFalsyAndZero:
(v) => (v || v === 0 ? v : undefined),
nonIsNaN:
(v) => (!isNaN(v) ? v : undefined),
typeofNumber:
(v) => (typeof v === 'number' ? v : undefined),
}
/* Using the <pre> element. */
function display(array) {
const text = array.map(valueAsText);;
document.getElementById('results').append(text + '\n');
}
Object.keys(approaches).forEach((name) => {
const results = batch.map(approaches[name]);
display(results);
});
/* Using the <table> element. */
function tableCell(text, elementType = 'td') {
const el = document.createElement(elementType);
el.textContent = text;
return el;
}
function arrayAsTableCells(array, elementType = 'td') {
return array.map((text) => tableCell(text, elementType));
}
function tableRow() {
return document.createElement('tr');
}
function valueAsText(value) {
if (value === undefined) {
return 'undefined';
}
if (value === null) {
return 'null';
}
if (typeof value === 'string') {
return JSON.stringify(value);
}
return value.toString();
}
const table = document.querySelector('table#results-table');
const thead = table.querySelector('thead');
const headerRow = tableRow();
headerRow.append(tableCell('', 'th'));
headerRow.append(...arrayAsTableCells(batch.map(valueAsText), 'th'));
thead.append(headerRow)
const tbody = table.querySelector('tbody');
Object.keys(approaches).forEach((name) => {
const results = batch.map(approaches[name]);
const approachRow = tableRow();
approachRow.append(tableCell(name, 'th'));
approachRow.append(...arrayAsTableCells(results.map(valueAsText)));
tbody.append(approachRow);
});