Skip to content

Commit 2b461b3

Browse files
committed
Implement processSearchQuery() function
1 parent 197e9dd commit 2b461b3

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

app/utils/search.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const KEYWORDS_PREFIX = 'keywords:';
2+
3+
/**
4+
* Process a search query string and extract filters like `keywords:`.
5+
*
6+
* @param {string} query
7+
* @return {{ q: string, keyword?: string, all_keywords?: string }}
8+
*/
9+
export function processSearchQuery(query) {
10+
let tokens = query.trim().split(/\s+/);
11+
12+
let queries = [];
13+
let keywords = [];
14+
for (let token of tokens) {
15+
if (token.startsWith(KEYWORDS_PREFIX)) {
16+
keywords = token
17+
.slice(KEYWORDS_PREFIX.length)
18+
.split(',')
19+
.map(it => it.trim())
20+
.filter(Boolean);
21+
} else {
22+
queries.push(token);
23+
}
24+
}
25+
26+
let result = { q: queries.join(' ') };
27+
if (keywords.length === 1) {
28+
result.keyword = keywords[0];
29+
} else if (keywords.length !== 0) {
30+
result.all_keywords = keywords.join(' ');
31+
}
32+
33+
return result;
34+
}

tests/utils/search-test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { module, test } from 'qunit';
2+
3+
import { processSearchQuery } from '../../utils/search';
4+
5+
module('processSearchQuery()', function () {
6+
const TESTS = [
7+
['foo', { q: 'foo' }],
8+
[' foo bar ', { q: 'foo bar' }],
9+
['foo keywords:bar', { q: 'foo', keyword: 'bar' }],
10+
['foo keywords:', { q: 'foo' }],
11+
['keywords:bar foo', { q: 'foo', keyword: 'bar' }],
12+
['foo \t keywords:bar baz', { q: 'foo baz', keyword: 'bar' }],
13+
['foo keywords:bar,baz', { q: 'foo', all_keywords: 'bar baz' }],
14+
['foo keywords:bar keywords:baz', { q: 'foo', keyword: 'baz' }],
15+
];
16+
17+
for (let [input, expectation] of TESTS) {
18+
test(input, function (assert) {
19+
assert.deepEqual(processSearchQuery(input), expectation);
20+
});
21+
}
22+
});

0 commit comments

Comments
 (0)