const MARKUP_TAG = /<[^>]*>/g const WORDS_ALLOWED_BETWEEN_QUOTE_WORDS = 3 export const RANK_BANDS = [1, 3, 5, 10] function wordsOf(text) { return text .replace(MARKUP_TAG, ' ') .normalize('NFKC') .toLowerCase() .split(/[^\p{L}\p{N}]+/u) .filter(word => word.length > 0) } function holdsInOrder(body, quote) { if (quote.length === 0) return true for (let start = 0; start < body.length; start += 1) { if (body[start] !== quote[0]) continue let position = start let matched = 1 while (matched < quote.length) { const limit = Math.min(body.length, position + 2 + WORDS_ALLOWED_BETWEEN_QUOTE_WORDS) const next = body.slice(position + 1, limit).indexOf(quote[matched]) if (next < 0) break position += next + 1 matched += 1 } if (matched === quote.length) return true } return false } export function holdsAnswer(question, path, text) { if (path !== question.file) return false const body = wordsOf(text) const quotes = Array.isArray(question.quote) ? question.quote : [question.quote] const alternatives = Array.isArray(question.alsoAccepted) ? question.alsoAccepted : [] const matches = quote => holdsInOrder(body, wordsOf(quote)) return quotes.every(matches) || alternatives.some(matches) } export function sideOutcome(question, results, searchable) { const rankWhere = test => { const index = results.findIndex(test) return index < 0 ? null : index + 1 } return { searchable, rank: searchable ? rankWhere(result => holdsAnswer(question, result.path, result.text)) : null, rightFileRank: searchable ? rankWhere(result => result.path === question.file) : null, characters: results.reduce((total, result) => total + result.text.length, 0), returned: results.length, files: results.map(result => result.path), } } export function tally(outcomes) { const ranks = outcomes.map(outcome => outcome.rank) return { questions: outcomes.length, fileNotSearchable: outcomes.filter(outcome => !outcome.searchable).length, ...Object.fromEntries( RANK_BANDS.map(band => [`withinTop${band}`, ranks.filter(rank => rank !== null && rank <= band).length]), ), missed: ranks.filter(rank => rank === null).length, meanCharacters: Math.round( outcomes.reduce((total, outcome) => total + outcome.characters, 0) / Math.max(outcomes.length, 1), ), } }