All files / mutxt-react/src/translit convert.ts

100% Statements 19/19
87.5% Branches 7/8
100% Functions 1/1
100% Lines 15/15

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 272x                 2x 86x 86x 86x 86x 429x 429x 429x   86x 86x 86x   86x 86x 86x    
import {CompiledScheme, Matcher} from './Matcher';
import type {TranslitScheme} from './types';
 
/**
 * One-shot convert a string from Latin to the target script.
 *
 * Useful for tests, batch transforms, search-input prefill, etc. For
 * keystroke-by-keystroke editing use `Matcher` directly.
 */
export const convert = (input: string, scheme: TranslitScheme | CompiledScheme): string => {
  const compiled = scheme instanceof CompiledScheme ? scheme : new CompiledScheme(scheme);
  const matcher = new Matcher(compiled);
  let out = '';
  for (const ch of input) {
    const step = matcher.feed(ch);
    if (step.replaceTail > 0) out = out.slice(0, out.length - step.replaceTail);
    out += step.emit;
  }
  const flushed = matcher.flushBuffer();
  if (flushed.replaceTail > 0) out = out.slice(0, out.length - flushed.replaceTail);
  out += flushed.emit;
  // Apply final-form to the last glyph.
  const finalForm = compiled.applyFinalForm(out);
  if (finalForm) out = out.slice(0, out.length - finalForm.tail) + finalForm.replacement;
  return out;
};