Archive for February, 2014

Usable search function

Alternative to Array and ArrayCollection inbuilt search method:

@whatToSearch – int/number/string value to search in target array/arraycollection whereToSearch.

@propToSearch – if array or arraycollection contains list of objects then propToSearch contains field name of object.

public static function search(whatToSearrch:*, whereToSearch:*, propToSearch:String, caseSensitive:Boolean=true):int
{
var index:int=-1;

if (whatToSearch == null || whereToSearch == null)
return index;

if (whatToSearch is String && String(whatToSearch).length == 0)
return index;

//CHECK CASE SENSITIVE SEARCH FOR STRING VALUE
var searchingFor:*=whatToSearch;

if (propToSearch == null || propToSearch.length == 0)
{
//search into whereToSearch without property
for (var i:int=0; i < whereToSearch.length; i++)
{
//string search
if(isNaN(whatToSearch))
{
if (whatToSearch is String && !caseSensitive)
{
//convert into upper case and then match
if (whereToSearch[i].toString().toUpperCase() == searchingFor.toString().toUpperCase())
{
index=i;
break;
}
}
else
{
if (whereToSearch[i] == searchingFor)
{
index=i;
break;
}
}
}else
{
//numeric search
//parse numeric value and then match
if(parseFloat(whereToSearch[i]) == parseFloat(searchingFor))
{
index=i;
break;
}
}
}
}
else
{
//search into whereToSearch with property
for (var j:int=0; j < whereToSearch.length; j++)
{
//string search
if(isNaN(whatToSearch))
{
if (whatToSearch is String && !caseSensitive)
{
if (String(whereToSearch[j][propToSearch]).toUpperCase() == searchingFor.toString().toUpperCase())
{
index=j;
break;
}
}
else
{
if (whereToSearch[j][propToSearch] == searchingFor)
{
index=j;
break;
}
}
}else
{
//numeric search
//parse numeric value and then match
if(parseFloat(whereToSearch[j][propToSearch]) == parseFloat(searchingFor))
{
index=j;
break;
}
}
}
}

return index;

}

Advertisements

Leave a comment