JS Split Varables - javascript

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

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)

Is there a way to name the same case but when is 2 times clicked?

I'm translating some interactives for a math school from English to Spanish. I'm having problems adapting the code to numbers in Spanish.
So I'm doing cases to change the order and the text (the numbers in Spanish have a different form to write between 20 and 24) in the console log the case "veinte" works to 20 but when you go 22 the case "veinte" count like 2 times "veinte" case. (see the image below)
I don't know how to make a x2 of the same case. Sorry if I don't know how to make a good explanation of my problem, it's kind of confusing.
for(i = 0 ; i < q.length ; i++)
{
if(q[i] != null)
{
if(LowerCase)
q[i] = q[i].toLowerCase();
switch((3 - q.length) + i)
{
case 0:
switch(q[i]){
case 'Cinco':
q[i] = 'Quinientos';
break;
case 'Siete':
q[i] = 'Setecientos';
break;
case 'Nueve':
q[i] = 'Novecientos'
break;
case 'Uno':
q[i] = 'Cien'
break;
default:
q[i] = q[i] + "cientos";
}
vTemp = o.substring(i + 1);
if(parseInt(vTemp) > 0)
//q[i] = q[i] + " and";
q[i] = q[i] + "";
break;
case 1:
switch(q[i]){
case 'veinte':
q[i] = 'veinti';
break;
default:
q[i] = q[i];
}
if((q[2] != null) && (q[2] != "x"))
q[i] = q[i] + " y";
break;
case 2:
if(q[i] == "x")
q[i] = "";
break;
}
LowerCase = true;
}
else
{
q[i] = "";
}
}

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."));

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

Convert from binary to hexadecimal in shortest amout of code [duplicate]

This question already has answers here:
JavaScript: Need functions to convert a string containing binary to hex, then convert back to binary
(4 answers)
Closed 9 years ago.
What is the easiest way to do this in Javascript? Currently my code is a giant switch block, is there an easier way?
Current code:
function convertBintoHex(input){
input = ""+input;
while(input.length < 8){
input = "0" + input;
}
input = [input.substring(0,4),input.substring(4,8)];
var output = "";
for(var i in input){
switch(input[i]){
case "0000":
output += 0;
break;
case "0001":
output += 1;
break;
case "0010":
output += 2;
break;
case "0011":
output += 3;
break;
case "0100":
output += 4;
break;
case "0101":
output += 5;
break;
case "0110":
output += 6;
break;
case "0111":
output += 7;
break;
case "1000":
output += 8;
break;
case "1001":
output += 9;
break;
case "1010":
output += 'A';
break;
case "1011":
output += 'B';
break;
case "1100":
output += 'C';
break;
case '1101':
output += 'D';
break;
case '1110':
output += 'E';
break;
case '1111':
output += 'F';
break;
}
}
while(output.charAt(0) == 0 && output.length > 1){
output = output.substring(1);
}
return "0x" + output;
}
Using built-in functions:
parseInt('1010101010', 2).toString(16)

Categories