All files / app processTerms.tsx

96.63% Statements 115/119
86.91% Branches 93/107
100% Functions 28/28
97.27% Lines 107/110

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249                88x 88x                 510x 510x 22183x 22183x 22183x 22183x 4713x             3698x     9792x 12538x 12538x 12538x   9792x 140181x 140181x 140181x   9792x 136162x 136162x 136162x         33280x 354060x 354060x       1210x 1210x 1210x 560x 560x 560x   1210x 6035x 6035x 6035x 6035x   1210x 4685x 4685x 4685x 4685x   1210x 194950x       9832x 9832x                                                             9832x 9792x 9792x 9792x   148153x   9792x   15608x   9792x 9792x 15608x 205564x     9792x   9792x     12538x 9792x   9832x       139x 139x           9943x 9943x 9832x   111x 111x                 111x 111x   111x 111x         18780x 18780x 18780x 18780x 18780x 9943x   18780x 18780x 1210x   18780x       426x 426x   426x                                           426x 426x 426x 307x     426x       717x 717x 717x 717x 717x 717x 717x 717x 717x 452x 452x 426x   452x   381x     452x 452x     717x      
import {timers} from './addedTerms'
import type {Dict} from './storage'
import type {TermResources} from './resources'
import {unpackSynsetMembers} from './synset'
import type {FixedTerm, FuzzyTerm} from './term'
import {globToRegex, prepareRegex, relativeFrequency, termBounds, wildcard} from './lib/utils'
import type {GridRow} from './table'
 
const Processed: {[index: string]: FuzzyTerm | FixedTerm} = {}
const PartialMatchMap: {[index: string]: string} = {}
 
export async function extractMatches(
  term: string,
  ex: RegExp,
  from: {[index: string]: string},
  out: string[] = [],
  limit = Infinity
) {
  const collapsed = from[ex.source[1] in from ? ex.source[1] : 'all']
  for (let match: RegExpExecArray | null, cleaned = ''; out.length < limit && (match = ex.exec(collapsed)); ) {
    cleaned = match[0].replace(termBounds, '')
    Eif (cleaned) {
      out.push(cleaned)
      if (term && !(cleaned in PartialMatchMap)) {
        PartialMatchMap[cleaned] = term
      }
    }
  }
}
 
export function getFuzzyParent(term: string) {
  return term in PartialMatchMap ? PartialMatchMap[term] : ''
}
function makeLookups({lemma, related, synset_terms, lookup}: FixedTerm) {
  lemma.forEach(term => {
    lookup.any[term] = true
    lookup.lemma[term] = true
    lookup.lemma_map.set(term, true)
  })
  related.forEach(term => {
    lookup.any[term] = true
    lookup.related[term] = true
    lookup.related_map.set(term, true)
  })
  synset_terms.forEach(term => {
    lookup.any[term] = true
    lookup.synset[term] = true
    lookup.synset_map.set(term, true)
  })
}
type LogicalObject = {[index: string]: boolean}
async function objectAppend(any: LogicalObject, to: LogicalObject, from: Map<string, boolean>) {
  from.forEach((_, k) => {
    any[k] = true
    to[k] = true
  })
}
async function makeExpandedLookups(processed: FixedTerm, data: TermResources) {
  const lookup = processed.lookup
  const any = lookup.any
  processed.lemma.forEach(term => {
    const relatedLookup = (getProcessedTerm(term, data) as FixedTerm).lookup
    objectAppend(any, lookup.lemma_related, relatedLookup.related_map)
    objectAppend(any, lookup.lemma_synset, relatedLookup.synset_map)
  })
  processed.related.forEach(term => {
    const relatedLookup = (getProcessedTerm(term, data) as FixedTerm).lookup
    objectAppend(any, lookup.related_lemma, relatedLookup.lemma_map)
    objectAppend(any, lookup.related_related, relatedLookup.related_map)
    objectAppend(any, lookup.related_synset, relatedLookup.synset_map)
  })
  processed.synset_terms.forEach(term => {
    const relatedLookup = (getProcessedTerm(term, data) as FixedTerm).lookup
    objectAppend(any, lookup.synset_lemma, relatedLookup.lemma_map)
    objectAppend(any, lookup.synset_related, relatedLookup.related_map)
    objectAppend(any, lookup.synset_synset, relatedLookup.synset_map)
  })
  lookup.expanded = true
  lookup.map = new Map(Object.keys(any).map(term => [term, true]))
}
 
function makeFixedTerm(term: string, data: TermResources) {
  const {terms, lemmas, termLookup, termAssociations, synsetInfo} = data
  const processed = {
    type: 'fixed',
    term: term,
    term_type: 'fixed',
    categories: {},
    recognized: false,
    index: terms && termLookup ? termLookup[term] || -1 : -1,
    lemma: [],
    related: [],
    synsets: [],
    synset_terms: [],
    lookup: {
      expanded: false,
      map: new Map(),
      any: {},
      lemma: {},
      lemma_map: new Map(),
      lemma_related: {},
      lemma_synset: {},
      related: {},
      related_map: new Map(),
      related_lemma: {},
      related_related: {},
      related_synset: {},
      synset: {},
      synset_map: new Map(),
      synset_lemma: {},
      synset_related: {},
      synset_synset: {},
    },
  } as FixedTerm
  if (termAssociations && synsetInfo && lemmas && terms && -1 !== processed.index) {
    processed.recognized = true
    const associated = termAssociations[processed.index]
    processed.related =
      associated && associated[0] && Array.isArray(associated[0])
        ? associated[0].filter((_, i) => !!i).map(index => terms[index - 1])
        : []
    processed.synsets =
      associated && associated[1]
        ? (Array.isArray(associated[1]) ? associated[1] : [associated[1]]).map(index => synsetInfo[index - 1])
        : []
    const senseRelated: Set<string> = new Set()
    processed.synsets.forEach(synset => {
      unpackSynsetMembers(synset, terms, synsetInfo).forEach(member => {
        if (member !== processed.term) senseRelated.add(member)
      })
    })
    processed.synset_terms = Array.from(senseRelated)
    const lemma =
      terms && lemmas && term in lemmas
        ? lemmas['number' === typeof lemmas[term] ? terms[lemmas[term] as number] : term]
        : []
    processed.lemma = 'number' === typeof lemma ? [terms[lemma]] : lemma.map(index => terms[index])
    makeLookups(processed)
  }
  return processed
}
 
function attemptRegex(term: string, flags?: string) {
  try {
    return new RegExp(term, flags)
  } catch {
    return term
  }
}
function processTerm(term: string | RegExp, data: TermResources) {
  const isString = 'string' === typeof term
  if (isString && !wildcard.test(term)) {
    return makeFixedTerm(term, data)
  } else {
    const processed = isString ? globToRegex(term) : term.source
    const container = {
      type: 'fuzzy',
      term_type: isString ? 'glob' : 'regex',
      term: isString ? term : term.source,
      categories: {},
      recognized: false,
      regex: attemptRegex(isString ? processed : prepareRegex(processed), 'g'),
      matches: [],
    } as FuzzyTerm
    Eif (data.collapsedTerms) {
      extractMatches(container.term, container.regex, data.collapsedTerms, container.matches)
    }
    container.recognized = !!container.matches.length
    return container
  }
}
 
export function getProcessedTerm(id: string | RegExp, data: TermResources, dict?: Dict, expand?: boolean) {
  const registered = 'string' === typeof id && dict && id in dict
  const term = registered && dict[id].term ? dict[id].term : id
  const type = registered && dict[id].type === 'regex' ? 'regex' : 'fixed'
  const key = term + '_' + type
  if (!(key in Processed)) {
    Processed[key] = processTerm(type === 'regex' ? attemptRegex(term as string) : (term as RegExp), data)
  }
  const processed = Processed[key]
  if (expand && processed.type === 'fixed' && !processed.lookup.expanded) {
    makeExpandedLookups(processed, data)
  }
  return processed
}
 
export async function makeRow(rows: GridRow[], index: number, id: string, dict: Dict, data: TermResources) {
  const processed = getProcessedTerm(id, data, dict)
  const dictEntry = dict[id]
  const row: GridRow =
    processed.type === 'fixed'
      ? {
          processed,
          dictEntry,
          id,
          term: dictEntry.term || id,
          sense: dictEntry.sense,
          matches: processed.recognized ? 1 : 0,
          ncats: Object.keys(dictEntry.categories).length,
          frequency: relativeFrequency(processed.index, data.terms && data.terms.length).toFixed(2),
          senses: processed.synsets.length,
          related: processed.related.length,
        }
      : {
          processed,
          dictEntry,
          id,
          term: dictEntry.term || id,
          sense: dictEntry.sense,
          matches: processed.matches.length,
          ncats: Object.keys(dictEntry.categories).length,
        }
  Eif (dictEntry.categories) {
    const cats = dictEntry.categories
    Object.keys(cats).forEach(cat => {
      row['category_' + cat] = cats[cat]
    })
  }
  rows[index] = row
}
 
export async function makeRows(dict: Dict, data: TermResources, progress?: (perc: number) => void) {
  clearTimeout(timers.dictionary)
  return new Promise<GridRow[]>(resolve => {
    const ids = Object.freeze(Object.keys(dict))
    const n_ids = ids.length
    const limit = 1000
    const rows: GridRow[] = new Array(n_ids)
    let i = 0
    let batch_i = 0
    const runBatch = () => {
      clearTimeout(timers.dictionary)
      for (; i < n_ids && batch_i < limit; i++, batch_i++) {
        makeRow(rows, i, ids[i], dict, data)
      }
      Iif (i !== n_ids) {
        batch_i = 0
        Iif (progress) progress(i / n_ids)
        timers.dictionary = setTimeout(runBatch, 0)
      } else {
        Iif (progress) progress(1)
        resolve(rows)
      }
    }
    timers.dictionary = setTimeout(runBatch, 0)
  })
}