I’ve got a function in an object like this:
arrayofElements: function(item) {
var result = [];
if (item.isA) {
result.push(new Div('aClass', labels['A']));
}
if (item.isC) {
result.push(new Div('cClass', labels['C']));
}
if (item.isD) {
result.push(new Div('dClass', labels['D']));
}
return result;
},
How can this be refactored? I dislike having to push() each item conditionally.
You could move the
is*properties to a sub-object so as to isolate them, and loop over the sub-object’s propertiesThe values in
item.iscould be the classes (as shown), or the values initem.iscould be objects with aclassproperty, or you could use the property namepas an index in another object to get the classes. Which depends largely on what theitems represent and what the element classes are most closely associated with.