else自动替换条件运算符

else自动替换条件运算符

本文介绍了用if / else自动替换条件运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特定的JS解析器(不在我的控件中)不理解嵌套的条件运算符语法,如下所示:

A specific JS parser (not in my control) does not understand nested conditional operator syntax like this:

return num === 1 ? condition ? condition : something : something;

因此,我想替换文件中的所有条件运算符(简单和嵌套)使用if / else块。我该怎么办呢? (Textmate或类似的regexp会有所帮助。)

Hence, I would like to replace all conditional operators (simple and nested) in a file with if/else blocks. How do I go about it? (A regexp for Textmate or similar would be helpful.)

推荐答案

我不认为这对正则表达式是可行的 - 你需要用它们解析整个JS表达式语法。当然你可以用它们来查找三元运算符的外观,但是替换它们需要手工完成。

I don't think this is possible with regular expressions - you would need to parse the whole JS expression grammar with them. Of course you might use them to find appearances of ternary operators, but replacing them would need to be done by hand.

这是因为条件运算符形成表达式,而if / else结构是语句。这意味着你需要在if-else周围解除包含三元运算符的语句。有两种解决方案可以转换一般

This is because conditional operators form expressions, while if/else structures are statements. That means you will need to lift the statement containing the ternary operator around the if-else. There are two solutions to transform the general




< some statement then-expression>

} else {

< some statement else-expression>

}


  • if( 条件

    helper = then-expression ;

    else

    helper = else-expression ;

    < some statement helper >


  • 选择哪一个取决于复杂性一些陈述(对于 return -statement我选择#1)。由于替换带来了自己的语法规则,您甚至可能需要调整周围的块。所有这些都不是一项微不足道的任务,只有当你已经有一个经过解析的AST进行转换时,imho才能自动化。

    Which of them to choose depends on the complexity of the some statement (for your return-statement I'd opt for #1). And since the replacements bring their own syntax rules, you even might need to adapt the surrounding blocks. All this is not a trivial task, and imho could be automated only if you already had a parsed AST to transform.

    这篇关于用if / else自动替换条件运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-16 00:41