Search code examples
javascriptunminify

Comma Operator to Semicolons


I have a chunk of javascript that has many comma operators, for example

"i".toString(), "e".toString(), "a".toString();

Is there a way with JavaScript to convert these to semicolons?

"i".toString(); "e".toString(); "a".toString();

Solution

  • This might seem like a cop-out answer... but I'd suggest against trying it. Doing any kind of string manipulation to change it would be virtually impossible. In addition to function definition argument lists, you'd also need to skip text in string literals or regex literals or function calls or array literals or object literals or variable declarations.... maybe even more. Regex can't handle it, turning on and off as you see keywords can't handle it.

    If you want to actually convert these, you really have to actually parse the code and figure out which ones are the comma operator. Moreover, there might be some cases where the comma's presence is relevant:

    var a = 10, 20;
    

    is not the same as

    var a = 10; 20;
    

    for example.

    So I really don't think you should try it. But if you do want to, I'd start by searching for a javascript parser (or writing one, it isn't super hard, but it'd probably take the better part of a day and might still be buggy). I'm pretty sure the more advanced minifiers like Google's include a parser, maybe their source will help.

    Then, you parse it to find the actual comma expressions. If the return value is used, leave it alone. If not, go ahead and replace them with expression statements, then regenerate the source code string. You could go ahead and format it based on scope indentation at this time too. It might end up looking pretty good. It'll just be a fair chunk of work.

    Here's a parser library written in JS: http://esprima.org/ (thanks to @torazaburo for this comment)