I have this JQuery / Javascript block of code to filter my list by search terms. It's very long and looks a little unprofessional. Is there a way I could simplify it?
Like with something ".contains()"?
If someone could point me in the right direction I'd greatly appreciate it. Thanks !
Heres the code; Ask me if you need more:
$.each(catalog.products,
function(index, value) {
if ((filterValue == '' || filterValue == null)
|| value.name.toUpperCase().indexOf(filterValue.toUpperCase()) != -1
|| value.brand.toUpperCase().indexOf(filterValue.toLocaleUpperCase()) != -1
|| value.category.toUpperCase().indexOf(filterValue.toUpperCase()) != -1
|| value.sport.toUpperCase().indexOf(filterValue.toUpperCase()) != -1)
{
items.push('<li id="' + index + '">' +
'<a data-identity="productId" href="./details.page?productId=' + index + '" >' +
'<img class="ui-li-thumb" src="' + value.thumbnail + '"/>' +
'<p>' + value.brand + '</p>' +
'<h3>' + value.name + '</h3>' +
'<span class="ui-li-count">' + value.price + ' $</span></li>') +
'</a>';
}
}
);
A straightforward way to 'simplify' the code would be
var filterUpper = !filterValue || filterValue.toUpperCase();
var test = function(s) {return s.toUpperCase().indexOf(filterUpper) != -1};
if (!filterValue || test(value.name) || test(value.brand) || test(value.category) || test(value.sport)) {
...
I suggest you to read the following refactoring patterns:
The idea is that you're trying to infer something on that if statement, and it's not an 'indexOf' it's a business rule, try to give that rule a name and put the code in a method that expresses the intention.
just my 0.02
The first thing I would do is note that the following code snippet:
(filterValue == '' || filterValue == null)
can be changed to
!filterValue
This is because a null or empty string variable is considered 'falsy' in javascript, ie when considered as a boolean these values convert to false.
Then I would do as Alexander Gessler [1] has done and factor out the filterValue.toUpperCase() which is repeated.
[1] Looking for a way to simplify an if statement with multiple ||
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.