Quote:
Originally Posted by felgall
In modern browsers that support the Array filter method you could use
|
you can omit return and function by using the native regexp method test():
Code:
names = ["AFGHANISTAN", "ALGERIA", "ARGENTINA", "BANGLADESH", "BRAZIL", "BURMA",
"CANADA", "CHINA", "COLUMBIA", "CONGO", "EGYPT", "ETHIOPIA", "FRANCE",
"GERMANY", "GHANA", "INDIA", "INDONESIA", "IRAN", "IRAQ", "ITALY",
"JAPAN", "KENYA", "MALAYSIA", "MEXICO", "MOROCCO", "NEPAL", "NIGERIA",
"NORTHKOREA", "PAKISTAN", "PERU", "PHILIPPINES", "POLAND", "RUSSIA",
"SAUDIARABIA", "SOUTHAFRICA", "SOUTHKOREA", "SPAIN", "SUDAN", "TAIWAN",
"TANZANIA", "THAILAND", "TURKEY", "UGANDA", "UKRAINE", "UNITEDKINGDOM",
"UNITEDSTATES", "UZBEKISTAN", "VENEZUELA", "VIETNAM", "YEMEN"];
function filterByLetter(originalList, letter){
return originalList.filter(/./.test, RegExp(letter));
}
filterByLetter(names, "U");
the pattern is not only less typing, it executes faster without the function call and closure overhead.
if you couldn't use a regexp method (an array of objects for example), it's better to use
this instead of a closure:
Code:
function filterByLetter(originalList, letter){
return originalList.filter(function(x) {return x.indexOf(this)===-1;}, letter);
}
since functions need
this anyway, avoiding the extra outside closure in the looped function can help the VM execute the code body faster.
the difference is that the version above is a
pure function, which is easier to optimize.
it also means we can breakup the loop code and maybe re-use it later.
the filter function is really examining something for something else, let's call it
contains():
Code:
function contains(x) {return x.indexOf(this)===-1;}
function hasLetter(originalList, letter){
return originalList.filter(contains, letter);
}
function hasClass(elm, strClassName){
return contains.call( strClassName, elm.className);
}
by making the logic pure,
contains() can pull double duty for the hasLetter() and hasClass() method.
we could also .filter[] an exploded classList, but i wanted to show a call example.
silly examples perhaps, but i hope to have made the point...