@@ -96,29 +96,27 @@ export function search(query) {
96
96
97
97
for ( let i = 0 ; i < data . length ; i ++ ) {
98
98
const post = data [ i ]
99
- let isMatch = false
99
+ let matchesScore = 0
100
100
let resultStr = ''
101
101
const postTitle = post . title && post . title . trim ( )
102
102
const postContent = post . body && post . body . trim ( )
103
103
const postUrl = post . slug || ''
104
104
105
- if ( postTitle && postContent ) {
106
- keywords . forEach ( keyword => {
105
+ if ( postTitle ) {
106
+ keywords . forEach ( keyword => {
107
107
// From https://github.com/sindresorhus/escape-string-regexp
108
108
const regEx = new RegExp (
109
109
keyword . replace ( / [ | \\ { } ( ) [ \] ^ $ + * ? . ] / g, '\\$&' ) ,
110
110
'gi'
111
- )
111
+ ) ;
112
112
let indexTitle = - 1
113
113
let indexContent = - 1
114
114
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
117
117
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 ;
122
120
if ( indexContent < 0 ) {
123
121
indexContent = 0
124
122
}
@@ -144,19 +142,20 @@ export function search(query) {
144
142
}
145
143
} )
146
144
147
- if ( isMatch ) {
145
+ if ( matchesScore > 0 ) {
148
146
const matchingPost = {
149
147
title : escapeHtml ( postTitle ) ,
150
- content : resultStr ,
151
- url : postUrl
148
+ content : postContent ? resultStr : '' ,
149
+ url : postUrl ,
150
+ score : matchesScore
152
151
}
153
152
154
153
matchingResults . push ( matchingPost )
155
154
}
156
155
}
157
156
}
158
157
159
- return matchingResults
158
+ return matchingResults . sort ( ( r1 , r2 ) => r2 . score - r1 . score ) ;
160
159
}
161
160
162
161
export function init ( config , vm ) {
0 commit comments