I have a JS function that takes JSON data and creates an HTML table. As my project developed, I needed one specific table to be created with a button - so I added an option to the function and an appropriate if
statement. Then I decided I wanted to add a table colour option - another option; another if
statement.
Finally, I now wish to add another option to colour rows depending on the content of the a parameter in each row of data. But that is ONLY for a specific set of JSON data that I will send - so I now need to add another option and a very specific if
statement to catch this table type.
What I'd like to know: is there a better way of doing this? Most of the code to create the table is generic so don't wish to create new functions for each use case. But the function is now becoming full of options and if
s and not sure if this considered bad practice.
Edit: after some further searching, I think I am asking about overloading best practices. But, from what I understand, overloading in JS is about having lots of if
s or switch...case
which is essentially I am not sure about the best way to do or if it is even appropriate.
Some code with questions in the comments (edited to keep it brief):
function CreateTableFromJSON(jData, colour, addBtnToCol) {
table.className = "ui collapsing striped table unstackable " + colour; // Adds the colour option.
// Add JSON data to the table as rows.
for (var i = 0; i < jData.length; i++) {
var tr = tbody.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
// This 'option' adds a button if the column is a particular value
// Is better practice to keep the main function (create table) generic and then call another (sub?) function to add the button to the created table?
if(col[j] === addBtnToCol){
var btnAdd = document.createElement('button');
btnAdd.type = "button";
tabCell.appendChild(btnAdd);
}
else
tabCell.innerHTML = jData[i][col[j]];
}
}
}