如何使Google Closure编译器恒定折叠以下内容?

时间:2019-06-08 12:12:28

标签: optimization google-closure-compiler google-closure constantfolding

请考虑以下JavaScript代码,该代码提供了类似Python的格式化功能“ format”。

/**
 * @param {string} pattern
 * @param {...string} var_args
 * @return {string} formatted string
 */
function format(pattern, var_args) {
  return pattern.replace(/{(\d+)}/g, (_, pos) => arguments[pos]);
}

console.log(format("{1}", "a"));

处于高级模式的Closure编译器(例如,v20190528)无法对其进行固定折叠并生成类似以下内容的东西。 (-O ADVANCED --language_out ECMASCRIPT5_STRICT --use_types_for_optimization)

'use strict';console.log(function(a,d){var b=arguments;return a.replace(/{(\d+)}/g,function(e,c){return b[c]})}("{1}","a"));

事实证明,闭包编译器完全在这里,因为String.replace方法未使用note注释为@nosideeffects“如果替换函数具有副作用,则这可能会产生副作用。 ”,这也是完全正确的。但是,即使将这个外部文件编辑为具有@nosideeffects批注,折叠也不会发生。什么可能会停止折叠,以及是否有解决方法?

0 个答案:

没有答案