import { escapeRegExp } from '../other/regexp.ts'; export class Replacer { private regexp: RegExp | undefined; private readonly map: Record; constructor(map: Record) { this.map = map; } private build() { if (this.regexp) { return; } const groups = Object.keys(this.map) .map(escapeRegExp) .sort((a, b) => b.length - a.length); const pattern = `(?:${groups.join('|')})`; this.regexp = new RegExp(pattern, 'g'); } replace(string: string): string { if (!string) { return ''; } this.build(); return string.replace(this.regexp!, (substring) => this.map[substring]); } }