Skip to content

Commit 61df4cb

Browse files
committed
Extract search to a file
1 parent 57af626 commit 61df4cb

File tree

2 files changed

+52
-9
lines changed

2 files changed

+52
-9
lines changed

src/util/Searcher.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
}

src/views/PopularRepositories.vue

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@
1212

1313
<script>
1414
import { mapState } from "vuex";
15-
import deburr from "lodash/deburr";
1615
import sortBy from "lodash/sortBy";
1716
import Repositories from "@/components/RepositoryCard";
1817
import InputSearch from "@/components/InputSearch";
18+
import Searcher from "@/util/Searcher";
19+
20+
const repoSearcher = new Searcher().setField("name").setField("description");
1921
2022
export default {
2123
name: "PopularRepositories",
@@ -37,14 +39,15 @@ export default {
3739
return this.repositories.slice(0, 10);
3840
}
3941
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
4851
}
4952
}
5053
};

0 commit comments

Comments
 (0)