File tree Expand file tree Collapse file tree 2 files changed +52
-9
lines changed Expand file tree Collapse file tree 2 files changed +52
-9
lines changed Original file line number Diff line number Diff line change
1
+ import deburr from "lodash/deburr" ;
2
+
3
+ export default class Searcher {
4
+ /**
5
+ * @param {Array }
6
+ */
7
+ fields = [ ] ;
8
+
9
+ /**
10
+ *
11
+ * @param {string } field
12
+ */
13
+ setField ( field ) {
14
+ this . fields . push ( field ) ;
15
+ return this ;
16
+ }
17
+
18
+ /**
19
+ *
20
+ * @param {Array } data
21
+ */
22
+ setData ( data ) {
23
+ this . data = data ;
24
+ return this ;
25
+ }
26
+
27
+ /**
28
+ *
29
+ * @param {string } searchTerm
30
+ * @returns {Array }
31
+ */
32
+ findAll ( searchTerm ) {
33
+ const matcher = new RegExp ( deburr ( searchTerm ) , "i" ) ;
34
+ const result = this . data . filter ( item => {
35
+ return this . fields . some ( field => matcher . test ( deburr ( item [ field ] ) ) ) ;
36
+ } ) ;
37
+
38
+ return result ;
39
+ }
40
+ }
Original file line number Diff line number Diff line change 12
12
13
13
<script >
14
14
import { mapState } from " vuex" ;
15
- import deburr from " lodash/deburr" ;
16
15
import sortBy from " lodash/sortBy" ;
17
16
import Repositories from " @/components/RepositoryCard" ;
18
17
import InputSearch from " @/components/InputSearch" ;
18
+ import Searcher from " @/util/Searcher" ;
19
+
20
+ const repoSearcher = new Searcher ().setField (" name" ).setField (" description" );
19
21
20
22
export default {
21
23
name: " PopularRepositories" ,
@@ -37,14 +39,15 @@ export default {
37
39
return this .repositories .slice (0 , 10 );
38
40
}
39
41
40
- // TODO: Improve the performance, I'm not happy with the current speed.
41
- // TODO Extract this to another file and make it modular.
42
- const matcher = new RegExp (deburr (this .searchTerm ), " i" );
43
- const filteredRepos = this .repositories .filter (repo => {
44
- return matcher .test (deburr (repo .name )) || matcher .test (deburr (repo .description ));
45
- });
46
-
47
- return sortBy (filteredRepos, repo => - repo .stargazers ).slice (0 , 10 );
42
+ return sortBy (repoSearcher .findAll (this .searchTerm ), repo => - repo .stargazers ).slice (0 , 10 );
43
+ }
44
+ },
45
+ watch: {
46
+ repositories: {
47
+ handler () {
48
+ repoSearcher .setData (this .repositories );
49
+ },
50
+ immediate: true
48
51
}
49
52
}
50
53
};
You can’t perform that action at this time.
0 commit comments