Skip to content Skip to sidebar Skip to footer

Simplifying Long Switch Statements

I need to brush up on my javascript because it is my weakest language, so I thought 'Hey lets make a simple 'translating' program to test my skills'. Well I was able to make it tra

Solution 1:

You could use an object with properties like

{
    a: 'z',
    b: 'y',
    c: 'x',
    // ...
    z: 'a'
}

Usage with the default value of ina[i].

ina[i] = object[ina[i]] || ina[i];

Solution 2:

You could use a couple string variables to map the letters.

functiontranslateLetter(input) {
    const untranslated = "abcdefghijklmnopqrstuvwxyz";
    const translated   = "zyxwvutsrqponmlkjihgfedcba";

    var i = untranslated.indexOf(input);
    return translated[i];
}

Solution 3:

The switch you're using has logic that can be implemented directly without needing the switch at all via simple math (I believe most modern JS interpreters should JIT away the actual method calls if this is a hot loop, so the cost there should be trivial):

varget = prompt("Enter what you would like to encode!","At the current time decoding is still a WIP").toLowerCase();
var ina = [...get];
for(i = 0; i < get.length; i++) {
    var code = get.charCodeAt(i);
    if (97 <= code && code <= 122) {  // 'a' and 'z' ordinal values// Invert lowercase letters with simple math and convert back to character
        ina[i] = String.fromCharCode((122 + 97) - code);
    }
    // No need to handle non-lowercase/non-ASCII since ina initialized to match get
}

Solution 4:

Just do the math on the ASCII character codes:

function main() {
    varget = prompt("Enter what you would like to encode!","At the current time decoding is still a WIP").toLowerCase();
    var ina = [...get];

    for (i = 0; i < get.length; i++) {
        var charNum = get.charCodeAt(i) - 96;

        if (charNum > 0 && charNum < 27) {
            ina[i] = String.fromCharCode((27 - charNum) + 96);
        }
    };

    var outa = ina.join("");
    document.getElementById("output").innerHTML = outa;
};    

Post a Comment for "Simplifying Long Switch Statements"