Terser: Counter in a for of loop, incorrectly compressed.

Created on 30 Sep 2019  路  6Comments  路  Source: terser/terser

Bug report or Feature request?

When a counter is used in a for-of loop, the resulting code does not properly increment the counter for every iteration. I found this when looping over a generator function, but narrowed it down to a simple loop.

Version (complete output of terser -V or specific git commit)

4.3.4

Complete CLI command or minify() options used

terser input.js --compress --output output.js

terser input

console.log('This should output 4.');
console.log(test(4));

function test(num) {
    let counter = -1;
    for (const generatorIndex of [0,1,2,3,4,5,6,7,8,9]) {
        counter++;
        if (generatorIndex === num) {
            return counter;
        }
    }
    return undefined;
}

terser output or error

function test(num){let counter=-1;for(const generatorIndex of[0,1,2,3,4,5,6,7,8,9])if(generatorIndex===num)return++counter}console.log("This should output 4."),console.log(test(4));

Console:

This should output 4.
0

Expected result

Console:

This should output 4.
4
bug

All 6 comments

Nice, thanks for this report!

This seems to happen only when sequences and collapse_vars are both true. The workaround is to disable one of them. You know, if I can't fix this right now.

It's a bit complicated. I probably won't be able to fix this quickly.

With 4.4.0, I am still encountering this issue when using the above code but with counter += 1; instead counter++;

@fabiosantoscode Can this be reopened If possible?

Certainly!

This has been fixed in some unrelated commit. It now works for counter += 1 and counter = counter + 1.

Was this page helpful?
0 / 5 - 0 ratings