I'm rewriting my old table sort library. In the library, I have this method which gets some attributes from the table:
<table data-sort-cols="" data-sort-orders="">
getSortInfo : function(element) {
switch (element.tagName) {
case "TABLE":
function getSortAttr(element, attr) {
var info = element.getAttribute(attr);
if (info != "") {
info = info.split(",").map(function(val) { return parseInt(val,10) });
} else {
info = [];
}
return info;
};
return {
columns : getSortAttr(element, "data-sort-cols"),
orders : getSortAttr(element, "data-sort-orders"),
}
I want to shorten the getSortAttr function. Function returns the assigned value (e.g. "1,3,2" -> [1,3,2]). If there is not an assigned value to the attribute, it returns an empty array. I want to get rid of the if statement.
Is there a way to modify this line, and make it return an empty array if the string is empty ""?
info = info.split(",").map(function(val) { return parseInt(val,10) });
I've tried
// returns [NaN]
"".split(",").map(function(val) {
return parseInt(val, 10);
})
// returns [undefined]
"".split(",").map(function(val) {
var num = parseInt(val, 10);
if (!isNaN(num) && isFinite(num)) {
return num;
}
})
but didn't work.
switchstatement.ifstatement? Checking the input once before the map seems better than using a filter as in the accepted answer, since that unnecessarily checks all the elements of the array.data-sort-xattributes are set at the initialization stage andgetSortInfomethod is called when the user clicks on a column header.data-sort-xis set to empty strings before any sorting; after a sort, it changes to "2,1" (column indexes or orders). If statement required for the first sorting. After that I thought it is redundant ... Though I'm not sure if what I'm looking for is a good practice.