Replace-Switches: Rewrites Switch Statements in JavaScript Code

This JS library makes translation of valid JavaScript code given as input in the following way: the library converts all switch statements present in the piece of code to loop and if statements. So, put simply, this library allows one to remove all switches from a JavaScript piece of code, while keeping the semantics of the code.

At the first glance, one can think that the solution should be easy like e.g. turning a switch statement into a simple if-elif-else statement. But this is not true if we remember the problems listed below. The thorough suite of unit-tests is present in the repository and checks a really vast number of testing cases. All the problems listed below have corresponding unit-tests in the suite:

Dependencies

JavaScript libraries esprima and escodegen are already present in the repository.

Usage

Usage of the library is extremely simple and can be seen in the file with the unit-tests. But the idea is present below:

const switchRemoval = require("./remove-switches");
var newSourceString = switchRemoval.removeSwitches(oldSourceString);

Example

The input of the unit-test #76 is the following:

function case1() {
    console.log("function case1() called");
    return 1;
}

function case2() {
    console.log("function case2() called");
    return 2;
}

switch (case1()) {
    case case1():
                console.log("case1");
    default:
                console.log("default");
    case case2():
                console.log("case2");
                break;
}console.log("end");

The resulting piece of code is the following:

function case1() {
    console.log('function case1() called');
    return 1;
}
function case2() {
    console.log('function case2() called');
    return 2;
}
do {
    const _uhbhl9pob = case1();
    if (_uhbhl9pob === case1()) {
        console.log('case1');
        console.log('default');
        console.log('case2');
        break;
        break;
    }
    if (_uhbhl9pob === case2()) {
        console.log('case2');
        break;
        break;
    }
    console.log('default');
    console.log('case2');
    break;
    break;
} while (false);
console.log('end');

The output of both the pieces of code is:

case1
default
case2
end