Files
shields/frontend/lib/prepare-examples.js
Paul Melnikow 7a664ca3e8 Run prettier (#1866)
Merging this separately so the commit with the tooling change is readable. This is a follow-on to #1167 which turned prettier on.
2018-08-08 17:57:14 -04:00

46 lines
1.1 KiB
JavaScript

import escapeStringRegexp from 'escape-string-regexp'
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 escaped = escapeStringRegexp(query)
const regex = new RegExp(escaped, '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
)
)
)
}