A better Each

2 views
Skip to first unread message

kstubs

unread,
Oct 6, 2008, 2:26:52 AM10/6/08
to Prototype & script.aculo.us
I have a JSON array list, I am matching the "Name" item against 1 or
more items in my match array.

Pseudo:

for each list.item
if item "Name" contains one and every (must match every item in array)
then: TRUE
return new item to filtered list


Example Data:
Apple Martini
Gin Martini
Slippery Nipple
T&T
Gin Fizz
A Gin X Martian

Example User Input:
gin

Result:
Gin Martini
Gin Fizz
A Gin X Martian

Example User Input:
gin mart

Result:
Gin Martini
A Gin X Martian

My code today:
list.row.each(function(row)
{
for(x = 0; x < aNames.length; x++)
{
found = true;

if(row.Name.toLowerCase().indexOf(aNames[x]) < 0)
found = false;

if(!found)
break;
}

if(found)
filterlist.row[filterlist.row.length] = row;
});


Thanks for the help! My code today is working, but seems to be slow
and maybe inefficient.

Karl..

T.J. Crowder

unread,
Oct 6, 2008, 5:17:47 AM10/6/08
to Prototype & script.aculo.us
Hi Karl,

The biggest issue I see there is what look like global variables:
Without 'var' statements in your closure, you're using implicitly-
declared global variables, which is a very bad idea. I haven't had
time to blog the last few months, but I have a post on this:
http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html

On the code, no *massive* inefficiencies jump out, but I would
probably do something like this if the list is long:

list.row.each(function(row)
{
var x, len;

for (len = aNames.length, x = 0; x < len; x++)
{
if (row.Name.toLowerCase().indexOf(aNames[x]) >= 0)
{
filterlist.row[filterlist.row.length] = row;
break;
}
}
});

I'm assuming 'filterlist' is in-scope for the closure; a global or a
local var in the enclosing function, that sort of thing.

Prototype's Enumerable module (which is mixed into Array) has a
collect method that is for this sort of thing, but I doubt it would be
more efficient than the above:
http://www.prototypejs.org/api/enumerable/collect

If you're seeing things being really slow, I suspect the problem may
be outside of the code you quoted.

HTH,
--
T.J. Crowder
tj / crowder software / com
Reply all
Reply to author
Forward
0 new messages