Simplifying Long Switch Statements - javascript

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 translate one way so far(I havent worked on untranslating the stuff people input), but anyway the way it does it is by a series of many cases inside a switch. Im wondering if there is anyway I can simplify the code instead of having a million switch cases. Thanks here is my code.
function main() {
var get = 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 < ina.length; i++) {
switch(ina[i]) {
case "a":
ina[i] = "z";
break;
case "b":
ina[i] = "y";
break;
case "c":
ina[i] = "x";
break;
case "d":
ina[i] = "w";
break;
case "e":
ina[i] = "v";
break;
case "f":
ina[i] = "u";
break;
case "g":
ina[i] = "t";
break;
case "h":
ina[i] = "s";
break;
case "i":
ina[i] = "r";
break;
case "j":
ina[i] = "q";
break;
case "k":
ina[i] = "p";
break;
case "l":
ina[i] = "o";
break;
case "m":
ina[i] = "n";
break;
case "n":
ina[i] = "m";
break;
case "o":
ina[i] = "l";
break;
case "p":
ina[i] = "k";
break;
case "q":
ina[i] = "j";
break;
case "r":
ina[i] = "i";
break;
case "s":
ina[i] = "h";
break;
case "t":
ina[i] = "g";
break;
case "u":
ina[i] = "f";
break;
case "v":
ina[i] = "e";
break;
case "w":
ina[i] = "d";
break;
case "x":
ina[i] = "c";
break;
case "y":
ina[i] = "b";
break;
case "z":
ina[i] = "a";
break;
default:
ina[i] = ina[i]
};
};
var outa = ina.join("");
document.getElementById("output").innerHTML = outa;
};

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];

You could use a couple string variables to map the letters.
function translateLetter(input) {
const untranslated = "abcdefghijklmnopqrstuvwxyz";
const translated = "zyxwvutsrqponmlkjihgfedcba";
var i = untranslated.indexOf(input);
return translated[i];
}

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):
var get = 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
}

Just do the math on the ASCII character codes:
function main() {
var get = 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;
};

Related

how to use switch statment

im new with JS and i read about the switch statement. i dont know how to use it
i got an exercise to complete.
got an array with numbers 1-10 and the result need to be with words like "one","two","three"..
Thats what i got so far :
function sayNum(){
let nameNumber = [1,2,3,4,5,6,7,8,9,10]
let text = '';
for(let i=0;i<nameNumber.length;i++){
switch(numbers) {
case "1":
text = "one";
break;
case "2":
text = "two";
break;
case "3":
text = "three";
break;
case "4":
text='four';
break;
case "5":
text = "five";
break;
case "6":
text = "six";
break;
case "7":
text = "seven";
break;
case "8":
text = "eight";
break;
case "9":
text = "nine";
break;
case "10":
text = "ten";
}
}
return text;
}
sayNum()
You could do it like this, for example:
function sayNum(){
let numbers = [1,2,3,4,5,6,7,8,9,10];
let result = [];
for(let i=0;i<numbers.length;i++) {
switch(numbers[i]) {
case 1:
text = "one";
break;
case 2:
text = "two";
break;
case 3:
text = "three";
break;
case 4:
text = "four";
break;
case 5:
text = "five";
break;
case 6:
text = "six";
break;
case 7:
text = "seven";
break;
case 8:
text = "eight";
break;
case 9:
text = "nine";
break;
case 10:
text = "ten";
break;
}
result.push(text);
}
return result;
}
let namedNumbers = sayNum();
console.info(namedNumbers);
This will:
Add the textual values to an array, representing each number in the source array
Return the resulting array to the caller
Log the result in the console
In the switch statement, you pass an 'expression' into the switch statement. The expression itself can be a string, a number, float, boolean etc. Now, the expression is compared to each of the case clause. And this is a 'strict' comparison. And that is the reason why your code was not working.
Firstly you were passing an undeclared variable, 'numbers' as the switch expression. Instead, you should be passing the ith element of the nameNumber[i] array like so: switch(nameNumber[i]){ }
And, secondly, in each of your case clauses, you are comparing the value to a string like "1", "2". But the switch expression is compared using strict equality === operator, therefore when your nameNumber array contains numbers and not strings, your 'case' clauses should also have numbers and not strings. That means case 1: instead of case "1":.
You can read more about the switch-case here: Switch Statement
I have fixed your code below with the changes I mentioned above. Please run the below code snippet to see how it works. Goodluck!
function sayNum(){
let nameNumber = [1,2,3,4,5,6,7,8,9,10]
let text = '';
for(let i=0;i<nameNumber.length;i++){
switch(nameNumber[i]) {
case 1:
text = "one";
break;
case 2:
text = "two";
break;
case 3:
text = "three";
break;
case 4:
text='four';
break;
case 5:
text = "five";
break;
case 6:
text = "six";
break;
case 7:
text = "seven";
break;
case 8:
text = "eight";
break;
case 9:
text = "nine";
break;
case 10:
text = "ten";
}
console.log(text);
}
return text;
}
sayNum();
Rather than using a switch, use if statement. Because in switch, break statement can be used to jump out of a loop.
let text = '';
function sayNum() {
let nameNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < nameNumber.length; i++) {
if(nameNumber[i] == 1){
text += `"one",`;
}
if(nameNumber[i] == 2){
text += `"two",`;
}
if(nameNumber[i] == 3){
text += `"three",`;
}
if(nameNumber[i] == 4){
text += `"four",`;
}
if(nameNumber[i] == 5){
text += `"five",`;
}
if(nameNumber[i] == 6){
text += `"six",`;
}
if(nameNumber[i] == 7){
text += `"seven",`;
}
if(nameNumber[i] == 8){
text += `"eight",`;
}
if(nameNumber[i] == 9){
text += `"nine",`;
}
if(nameNumber[i] == 10){
text += `"ten"`;
}
}
}
sayNum();
console.log(text)

Mapping numeral marks to letter based marks

I'm trying to code a program to receive a number and map it to a letter grade based mark using javascript, and html.
When I run the code, I don't get any answers.
Here is the code:
HTML
<h1>mapping a numerical grade to a letter grade</h1>
</header>
<div class="column1">
<div class="input">
a <input id="number1" type="number" min=" -32768" max=" 32767" />
</div>
<div class="input">
<button onclick="mapping()">enter</button>
</div>
<strong><p id="output"></p></strong>
</div>
Javascript
function mapping() {
var a = parseInt(document.getElementById("number1").value);
switch (true) {
case a > 89:
answer = "A+";
break;
case a > 79:
answer = "A";
break;
case a > 74:
answer = "B+";
break;
case a > 69:
answer = "B";
break;
case a > 64:
answer = "C+";
break;
case a > 59:
answer = "C";
case a > 54:
answer = "D+";
case a > 49:
answer = "D";
break;
case a > 40:
answer = "E";
break;
default:
answer = "F";
document.getElementById("output").innerHTML = answer;
}
document.getElementById("output").innerHTML = answer; is inside the switch statement. It will be executed with default only
This code will work:
function mapping() {
var a = parseInt(document.getElementById("number1").value);
switch (true) {
case a > 89:
answer = "A+";
break;
case a > 79:
answer = "A";
break;
case a > 74:
answer = "B+";
break;
case a > 69:
answer = "B";
break;
case a > 64:
answer = "C+";
break;
case a > 59:
answer = "C";
case a > 54:
answer = "D+";
case a > 49:
answer = "D";
break;
case a > 40:
answer = "E";
break;
default:
answer = "F";
}
document.getElementById("output").innerHTML = answer;
}
switch (true) doesn't work. switch (1) does.
Also, I think case only accepts values, not comparisons -- at least when I tried it with Chrome and Opera. So you might want to rewrite this using if-else statements.

JS Split Varables

I have a String like "iyxnhel2jeh" and i want to for each 2 byte I want to split those into a single var.
var string = "iyxnhel2jehe";
var final = "";
while (/*String still has bits*/) {
switch (/*Two byte of string*/) {
case "iy":
final += "x";
break;
case "xn":
final += "o";
break;
case "he":
final += "g";
break;
case "l2":
final += "k";
break;
case "je":
final += "e";
break;
default:
final += "none"
}
}
Whats the best way to cut this string?
You could use regex to split string into 2letter parts, map them onto the characters from switch statement and join array back together, however the optimal way to do that would be to get rid of the switch statement and instead use those sequences of characters as keys of a object.
var string = "iyxnhel2jehe";
var final = string.match(/.{1,2}/g).map(twoletters => {
return {
"iy": "x",
"xn": "o",
"he": "g",
"l2": "k",
"je": "e"
}[twoletters] || "none";
}).join("");
console.log(final)
I'm not sure about the best way, but the following would do what you want...
var string = "iyxnhel2jehe";
var final = "";
for (var i = 0; i < string.length; i+=2) {
switch (string.substr(i,2)) {
case "iy":
final += "x";
break;
case "xn":
final += "o";
break;
case "he":
final += "g";
break;
case "l2":
final += "k";
break;
case "je":
final += "e";
break;
default:
final += "none"
}
}
console.log(final);
var string = "iyxnhel2jehe";
var final = "";
var offset = 0;
while (offset < string.length) {
switch (string.slice(offset, offset + 2)) {
case "iy":
final += "x";
break;
case "xn":
final += "o";
break;
case "he":
final += "g";
break;
case "l2":
final += "k";
break;
case "je":
final += "e";
break;
default:
final += "none"
}
offset += 2;
}
console.log(final);
Instead of trying to consume characters and check whether there are still any left, try splitting the string into 2-character chunks first, and loop through the array:
const s = "iyxnhel2jehe";
let final = "";
const t = s.split('');
const segments = t.map((e, i) => i % 2 === 0 ?
e + (t.length - 1 >= i + 1 ? t[i + 1] : '') :
null)
.filter(x => x != null);
segments.forEach(sg => {
console.log(sg);
switch (sg) {
case "iy":
final += "x";
break;
case "xn":
final += "o";
break;
case "he":
final += "g";
break;
case "l2":
final += "k";
break;
case "je":
final += "e";
break;
default:
final += "none"
}
});
console.log(final);

ROT13 cipher in as few lines of code possible

I have written a function where the values of the letters in a received string are shifted by 13 places.
My solution is highly inefficient and would need completely rewriting if the shift factor was changed.
Here is my solution:
function rot13(str) {
var charArray = str.split("");
var myArray = [];
for (var i = 0; i < charArray.length; i++) {
switch (charArray[i]) {
case "A":
myArray.push("N");
break;
case "B":
myArray.push("O");
break;
case "C":
myArray.push("P");
break;
case "D":
myArray.push("Q");
break;
case "E":
myArray.push("R");
break;
case "F":
myArray.push("S");
break;
case "G":
myArray.push("T");
break;
case "H":
myArray.push("U");
break;
case "I":
myArray.push("V");
break;
case "J":
myArray.push("W");
break;
case "K":
myArray.push("X");
break;
case "L":
myArray.push("Y");
break;
case "M":
myArray.push("Z");
break;
case "N":
myArray.push("A");
break;
case "O":
myArray.push("B");
break;
case "P":
myArray.push("C");
break;
case "Q":
myArray.push("D");
break;
case "R":
myArray.push("E");
break;
case "S":
myArray.push("F");
break;
case "T":
myArray.push("G");
break;
case "U":
myArray.push("H");
break;
case "V":
myArray.push("I");
break;
case "W":
myArray.push("J");
break;
case "X":
myArray.push("K");
break;
case "Y":
myArray.push("L");
break;
case "Z":
myArray.push("M");
break;
case " ":
myArray.push(" ");
break;
case ",":
myArray.push(",");
break;
case "!":
myArray.push("!");
break;
case "?":
myArray.push("?");
break;
case ".":
myArray.push(".");
break;
}
}
console.log(myArray.join(""));
}
rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK.");
Can you show me a more efficient less cumbersome solution?
Here's one possible implementation, with the ability to pass in any (positive) rotation value and a table of other replacements. Written in ES6.
function rotn(str, rotation = 13, map = {}) {
const table = {}; // New table, to avoid mutating the parameter passed in
// Establish mappings for the characters passed in initially
for (var key in map) {
table[map[key]] = key;
table[key] = map[key];
}
// Then build the rotation map.
// 65 and 97 are the character codes for A and a, respectively.
for (var i = 0; i < 26; i++) {
table[String.fromCharCode(65 + i)] = String.fromCharCode(65 + (i + rotation) % 26);
table[String.fromCharCode(97 + i)] = String.fromCharCode(97 + (i + rotation) % 26);
}
return str.split('').map((c) => table[c] || c).join('');
}
console.log(rotn("Gur dhvpx oebja Qbt whzcrq bire gur ynml Sbk.", 13, {'.': '!'}));
Here is an example using the reduce function:
function rot13(str) {
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
return str.split("").reduce(function(a, b) {
if (chars.indexOf(b) == -1) {
return a + b;
}
return a + chars[(chars.indexOf(b)+13) % chars.length]
}, "");
}
console.log(rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK."));
function ROT13 (str){
var result = "";
for (var i = 0; i < str.length; i++) {
var charCode = str.charCodeAt(i);
if (charCode >= 65 && charCode <= 90) {
result += String.fromCharCode(((charCode - 65 + 13) % 26) + 65);
} else if (charCode >= 97 && charCode <= 122) {
result += String.fromCharCode(((charCode - 97 + 13) % 26) + 97);
} else {
result += str[i];
}
}
return result;
}
Here's a solution that uses:
replace() with a /[a-z]/ regex so that only alphabetic characters will be modified
indexOf() to convert that alphabetic character to an index
then uses that index to lookup the corresponding cipher character
function rot13(txt) {
return txt.replace(/[a-z]/gi, c =>
"NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
[ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(c) ] );
}
console.log(rot13("GUR DHVPX OEBJA QBT WHZCRQ BIRE GUR YNML SBK."));

Compare if a-z or A-Z and give output with switch JavaScript function

I'm learning JavaScript. Very new and know basic. I'm playing with various options of JavaScript.
I'm comparing a-z (lower case) and A-Z (upper case) from user input. and giving an answer base on the input.
Normally i can do this with this long code:
var x = prompt("Enter Your character");
switch (x) {
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
document.write("Lower case");
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
document.write("Upper case");
break;
default:
document.write("It is number");
break;
}
With switch I want to achieve same output but with less code! Something like this:
var x = prompt("Enter Your character");
switch(x) {
case x >= 'a'|| x <= 'z':
document.write("Lower case");
break;
case x >= 'A' || x <= 'Z':
document.write("Upper case");
break;
default:
document.write("It is number");
break;
}
Any Help?
Please I want to do this with only switch function. I know i can do this with if/else function but i want to do this with switch. If its not possible with switch let me know :-)
The switch statement compares the input expression with each case statement using strict comparison.
So use true inside the switch clause and specify expressions that evaluate to true in case clause:
var x = prompt("Enter Your character");
switch (true) {
case x >= "a" && x <= "z":
alert("Lower case");
break;
case x >= "A" && x <= "Z":
alert("Upper case");
break;
default:
alert("Something else");
break;
}
I personally do not recommend this. This is only for learning.
You can try it with something like this.
<script>
var x=prompt("Enter Your character");
if (x.test(/[a-z]/)) {
document.write("Lower case");
} else if (x.test(/[A-Z]/)) {
document.write("Upper case");
} else {
document.write("It is number");
}
</script>
You can see more info here: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
You could do a simple if/else
var x=prompt("Enter Your character");
if(!isNaN(x))
console.log("It is number");
else if(x.toLowerCase()==x)
console.log("Lower case");
else if(x.toUpperCase()==x)
console.log("Upper case"););
Check if the character is in in between other characters:
var x=prompt("Enter Your character");
if (x >= '0' && x <= '9')
alert("number!");
else if(x >= 'a' && x <= 'z')
alert("lowercase!");
else if(x >= 'A' && x <= 'Z')
alert("uppercase!");
else
alert("not a letter!");
The parameter to a case statement is something to perform an equality comparison with, you don't put a comparison there. If you want to do a comparison, use if, not switch. Also, you should be combining the comparisons with &&, not ||
if (x >= 'a' && x <= 'z') {
document.write('Lower case');
} else if (x >= 'A' && x <= 'Z') {
document.write('Upper case');
} else if (x >= '0' && x <= '9') {
documennt.write('Number');
} else {
document.write('Something else');
}
Try also:
var x = prompt("Enter Your character");
var find = x.match(/([a-z]*)([A-Z]*)([0-9]*)/);
var type = ["Lower case","Upper case", "It is number"];
document.write(find ? type[find.lastIndexOf(x)-1] : "Unknown char")

Categories