-
Notifications
You must be signed in to change notification settings - Fork 1
/
DataSearch.js
95 lines (77 loc) · 2.4 KB
/
DataSearch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/** @see https://github.com/llh1/DataSearch/tree/master */
(function(global) {
var _getIndexedDataset = function(dataset) {
var indexedDataset = {};
for(var i=0; i<dataset.length; i++) {
indexedDataset[i] = dataset[i];
}
return indexedDataset;
};
var _getSearchData = function(indexedDataset) {
var searchData = "";
Object.keys(indexedDataset).forEach(function(index) {
var item = indexedDataset[index],
values = [];
if(_isValidSimpleType(item)) {
values.push(item);
} else if(_isObject(item)) {
values = _toFlattenArray(item);
} else {
throw new Error(typeof(item) + " data is not supported");
}
searchData += '"' + index + ' ' + values.join(" ") + '"';
});
return searchData;
};
var _isValidSimpleType = function(value) {
return typeof value === "string" || typeof value === "number";
};
var _isObject = function(value) {
return typeof value === "object";
};
var _toFlattenArray = function(hash) {
return Object.keys(hash).reduce(function(memo, key) {
var value = hash[key];
if(_isValidSimpleType(value)) {
memo.push(value);
return memo;
} else if(_isObject(value)) {
return memo.concat(_toFlattenArray(value));
}
}, []);
};
var DataSearch = function(dataset, options) {
this.dataset = dataset;
this.options = options || {};
this.indexedDataset = _getIndexedDataset(dataset);
this.searchData = _getSearchData(this.indexedDataset);
};
DataSearch.prototype.search = function(query) {
var keywords = query.split(" "),
lookaheadKeywordsRegex = "";
keywords.forEach(function(keyword) {
if(keyword !== "") {
lookaheadKeywordsRegex += '(?=[^"]* ' + keyword + '[^"]*)';
}
});
var searchRegex = new RegExp('"' + lookaheadKeywordsRegex + '([0-9]+)[^"]*"', 'gi');
var resultIds = [];
while(result = searchRegex.exec(this.searchData)) {
resultIds.push(parseInt(result[1]));
}
var results = [];
resultIds.forEach(function(id) {
results.push(this.indexedDataset[id]);
}.bind(this));
return results;
};
if(typeof exports === 'object') {
module.exports = DataSearch;
} else if (typeof define === 'function' && define.amd) {
define(function() {
return DataSearch;
})
} else {
global.DataSearch = DataSearch;
}
})(this);