浏览代码

Improves perf of interpolate (drastically) 🔥

main
Eric Amodio 5 年前
父节点
当前提交
ceadcf3c81
共有 1 个文件被更改,包括 12 次插入4 次删除
  1. +12
    -4
      src/system/string.ts

+ 12
- 4
src/system/string.ts 查看文件

@ -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;
@ -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> {

正在加载...
取消
保存