View Single Post
Old 12-01-2012, 11:26 AM   PM User | #4
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,554
Thanks: 9
Thanked 480 Times in 463 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by felgall View Post
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...
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:15.2% IE7:0.5% IE8:8.4% IE9:8.5% IE10:8.5%

Last edited by rnd me; 12-01-2012 at 12:06 PM..
rnd me is offline   Reply With Quote