【发布时间】:2011-11-14 21:55:41
【问题描述】:
这是一个简化的示例,但我正在开发一个输出 javascript 的代码翻译器。由于解析的方式,我必须分段输出翻译。 IE。我最终得到了一个类似于以下内容但更长的 javascript 文件:
function coolfunc() {
var result = "";
greet = function(user,town) {
var output = '';
output += 'Welcome ' + user + '!';
output += 'How is the weather in ' + town + '?';
return output;
}
goobye = function(user,town) {
var output = '';
output += 'Farewell ' + user + '!';
output += 'Enjoy the weather in ' + town + '!';
return output;
}
result += "Some output 1";
result += "Some output 2";
result += greet("Larry","Cool town");
result += goobye("Larry","Cool town");
return result;
}
是否有任何后处理器可以用来将上述内容压缩成如下内容:
function coolfunc() {
greet = function(user,town) {
var output = 'Welcome ' + user + '!'+'How is the weather in ' + town + '?';
return output;
}
goobye = function(user,town) {
var output = 'Farewell ' + user + '!'+'Enjoy the weather in ' + town + '!';
return output;
}
var result = "Some output 1"+"Some output 2"+greet("Larry","Cool town")+goobye("Larry","Cool town");
return result;
}
如果它可以组合相邻的静态字符串连接,那将是肉汁。
我认为 yuicompressor 或闭包编译器会这样做,但据我所知他们不会。
编辑:
到目前为止,评论似乎告诉我要在翻译器中执行此操作。我不认为这是最好的选择,因为它会使阅读翻译变得非常困难......类似于人们编写冗长代码然后将其缩小以用于生产的原因。
【问题讨论】:
-
您是否担心性能或带宽?因为这在性能方面真的没什么大不了的……
-
试试模板引擎;它应该更好地将代码和标记/消息分开,并且可能会稍微提高性能。
-
@Matchu:带宽。这没什么大不了的,但保留所有不必要的变量名似乎很愚蠢。
-
@davin:这对我没有帮助,但感谢您阅读我的问题。
-
这肯定看起来更容易在翻译器中修复,而不是从头开始重新解析 javascript 以尝试修复它。
标签: javascript optimization string-concatenation