Skip to content

Instantly share code, notes, and snippets.

@wonglok
Last active August 29, 2015 14:02
Show Gist options
  • Save wonglok/914851fe3df5e1526099 to your computer and use it in GitHub Desktop.
Save wonglok/914851fe3df5e1526099 to your computer and use it in GitHub Desktop.
AngularDart WildCardFilter :)
library wildcard_filter;
import 'package:angular/angular.dart';
class WildcardFilter{
static final String DEFAULT_SEPARATOR = ' ';
/*
* AngularJS Filter fnc "call"
*
* for a list of object, and a query string.
* 1. queryString break down into framgnets [getFragment]
* 2. the list of object would be filtered by fragmnets multiple times.
*/
List call(itemList, queryStr) {
if (queryStr == null){
return itemList;
}else{
if (itemList is Iterable && queryStr is String) {
List fragments = getFragments(queryStr);
List tempList = itemList;
fragments.forEach((fQuery){
tempList = tempList.where(
(item) => testRules(item, fQuery)
).toList();
});
return tempList.toList();
}
return const [];
}
}
/*
* Breakdown a [query] string and produce a list of fragments
*/
List getFragments(String query){
List<String> fragList = query.trim().split(DEFAULT_SEPARATOR);
return fragList;
}
/*
* match string in string
*/
bool matchStr(String target, String query){
return target.toLowerCase().contains(query.toLowerCase());
}
/*
* match string in txtList
*/
bool matchStrList(List<String> target, String query){
for(var item in target){
if(matchStr(item, query)){
return true;
}
}
return false;
}
/*
* Rules/Criteria to filter result.
*/
bool testRules(item, fQuery){
return (
false
// || matchStr(item.name, fQuery)
// || matchStr(item.directions, fQuery)
// || matchStrList(item.ingredients, fQuery)
// || matchStr(item.toJson.toString(), fQuery) //search anything :)
);
}
}
@Formatter(name: 'wildcardNamefilter')
class WildcardNameFilter extends WildcardFilter{
/*
* Rules/Criteria to filter result.
*/
bool testRules(item, fQuery){
return (
false
|| matchStr(item.name, fQuery)
|| matchStr(item.directions, fQuery)
|| matchStrList(item.ingredients, fQuery)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment