blob: 99626ddf08c20f1d80f7f015fed738ed38a4d362 [file] [log] [blame]
bigbiffd006b302015-03-06 18:36:03 -05001module.exports = function Searcher(){
2 var self = this;
3
4 var matches = [];
5
6 var fuzzy = false;
7 var limit = 10;
8
9 var fuzzySearchStrategy = require('./SearchStrategies/fuzzy');
10 var literalSearchStrategy = require('./SearchStrategies/literal');
11
12 self.setFuzzy = function(_fuzzy){ fuzzy = !!_fuzzy; };
13
14 self.setLimit = function(_limit){ limit = parseInt(_limit,10) || limit; };
15
16 self.search = function(data,crit){
17 if( !crit ) return [];
18 matches.length = 0;
19 return findMatches(data,crit,getSearchStrategy());
20 };
21
22 function findMatches(store,crit,strategy){
23 var data = store.get();
24 for(var i = 0; i < data.length && matches.length < limit; i++) {
25 findMatchesInObject(data[i],crit,strategy);
26 }
27 return matches;
28 }
29
30 function findMatchesInObject(obj,crit,strategy){
31 for(var key in obj) {
32 if( strategy.matches(obj[key], crit) ){
33 matches.push(obj);
34 break;
35 }
36 }
37 }
38
39 function getSearchStrategy(){
40 return fuzzy ? fuzzySearchStrategy : literalSearchStrategy;
41 }
42};