Skip to content

Commit

Permalink
Improves perf of interpolate (drastically) 🔥
Browse files Browse the repository at this point in the history
  • Loading branch information
eamodio committed Jul 19, 2019
1 parent 95fbe81 commit ceadcf3
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/system/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export namespace Strings {
const pathStripTrailingSlashRegex = /\/$/g;
const tokenRegex = /\$\{(\W*)?([^|]*?)(?:\|(\d+)(-|\?)?)?(\W*)?\}/g;
const tokenSanitizeRegex = /\$\{(?:\W*)?(\w*?)(?:[\W\d]*)\}/g;
// eslint-disable-next-line no-template-curly-in-string
const tokenSanitizeReplacement = '$${this.$1}';

export interface TokenOptions {
collapseWhitespace: boolean;
Expand Down Expand Up @@ -72,13 +74,19 @@ export namespace Strings {
return tokens;
}

const interpolationMap = new Map<string, Function>();

export function interpolate(template: string, context: object | undefined): string {
if (!template) return template;
if (template == null || template.length === 0) return template;
if (context === undefined) return template.replace(tokenSanitizeRegex, emptyStr);

// eslint-disable-next-line no-template-curly-in-string
template = template.replace(tokenSanitizeRegex, '$${this.$1}');
return new Function(`return \`${template}\`;`).call(context);
let fn = interpolationMap.get(template);
if (fn === undefined) {
fn = new Function(`return \`${template.replace(tokenSanitizeRegex, tokenSanitizeReplacement)}\`;`);
interpolationMap.set(template, fn);
}

return fn.call(context);
}

export function* lines(s: string): IterableIterator<string> {
Expand Down

0 comments on commit ceadcf3

Please sign in to comment.