Files
shields/frontend/lib/prepare-examples.js
Paul Melnikow 105e383d93 Improve search performance (#1393)
Add a class which applies display: none to badges we don’t want to see. This is accomplished by passing a `shouldDisplay` function along with each badge, which pulls the current query through a closure and applies it.

A bit roundabout, but it works.

The rest of the changes are refactors to avoid code duplication.

I decreased the debouce rate to 50, which seems to work well.

Fix #1314
2017-12-26 23:53:15 -05:00

34 lines
976 B
JavaScript

export function exampleMatchesRegex(example, regex) {
const { title, keywords } = example;
const haystack = [title].concat(keywords).join(' ');
return regex.test(haystack);
}
export function predicateFromQuery(query) {
if (query) {
const regex = new RegExp(query, 'i'); // Case-insensitive.
return example => exampleMatchesRegex(example, regex);
} else {
return () => true;
}
}
export function mapExamples(categories, iteratee) {
return categories
.map(({ category, examples }) => ({
category,
examples: iteratee(examples),
}))
// Remove empty categories.
.filter(({ category, examples }) => examples.length > 0);
}
export function prepareExamples(categories, predicateProvider) {
let nextKey = 0;
return mapExamples(categories, examples => examples.map(example => Object.assign({
shouldDisplay: () => predicateProvider()(example),
// Assign each example a unique ID.
key: nextKey++,
}, example)));
}