Skip to content

Commit 76825a7

Browse files
spiontimaschew
authored andcommitted
add scoring and sort to search plugin
1 parent 7276339 commit 76825a7

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

src/plugins/search/search.js

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -96,29 +96,27 @@ export function search(query) {
9696

9797
for (let i = 0; i < data.length; i++) {
9898
const post = data[i]
99-
let isMatch = false
99+
let matchesScore = 0
100100
let resultStr = ''
101101
const postTitle = post.title && post.title.trim()
102102
const postContent = post.body && post.body.trim()
103103
const postUrl = post.slug || ''
104104

105-
if (postTitle && postContent) {
106-
keywords.forEach(keyword => {
105+
if (postTitle) {
106+
keywords.forEach( keyword => {
107107
// From https://github.com/sindresorhus/escape-string-regexp
108108
const regEx = new RegExp(
109109
keyword.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'),
110110
'gi'
111-
)
111+
);
112112
let indexTitle = -1
113113
let indexContent = -1
114114

115-
indexTitle = postTitle && postTitle.search(regEx)
116-
indexContent = postContent && postContent.search(regEx)
115+
indexTitle = postTitle ? postTitle.search(regEx) : -1
116+
indexContent = postContent ? postContent.search(regEx) : -1
117117

118-
if (indexTitle < 0 && indexContent < 0) {
119-
isMatch = false
120-
} else {
121-
isMatch = true
118+
if (indexTitle >= 0 || indexContent >= 0) {
119+
matchesScore += indexTitle >= 0 ? 3 : indexContent >= 0 ? 2 : 0;
122120
if (indexContent < 0) {
123121
indexContent = 0
124122
}
@@ -144,19 +142,20 @@ export function search(query) {
144142
}
145143
})
146144

147-
if (isMatch) {
145+
if (matchesScore > 0) {
148146
const matchingPost = {
149147
title: escapeHtml(postTitle),
150-
content: resultStr,
151-
url: postUrl
148+
content: postContent ? resultStr : '',
149+
url: postUrl,
150+
score: matchesScore
152151
}
153152

154153
matchingResults.push(matchingPost)
155154
}
156155
}
157156
}
158157

159-
return matchingResults
158+
return matchingResults.sort((r1, r2) => r2.score - r1.score);
160159
}
161160

162161
export function init(config, vm) {

0 commit comments

Comments
 (0)