Can I implement/put an array on a switch conditional? - javascript

I was building my code when came to my mind a bizarre idea, can I implement/put an array inside a switch?
I mean, how can I make the codeHide case work? with this piece of code it don't work.
When I ask to set the command and I put hide() (that is codeHide[0] on the codeHide array) I want to switch take the codeHide case (my if-statement) and return an alert telling me the alertMessage of that particular array element.
If I put hide(background) (that is codeHide[1] on the codeHide array) I want to switch take the codeHide case else (of my if-statement) and return an alert telling me the alertMessage of that particular array element(in the is-statement).
Hope you understand me.
Doing this it don't work and I think it's because the "case codeHide:".
And this is what I've done so far:
var codeHide = ['hide()', 'hide(background)'];
$(".code").on("click", function () {
var codePrompt = prompt("Set the code in the command line."),
alertMessage = "",
consoleMessage = "Used '" + codePrompt + "' command.";
switch (codePrompt) {
case codeHide:
if (codeHide[0]) {
alertMessage = "Hiding elements...";
} else {
alertMessage = "Hiding Background...";
}
break;
default:
alertMessage = consoleMessage = "We are sorry but you entered a WRONG command, try again tho!\ntyped: " + codePrompt;
break;
}
alert(alertMessage);
console.log(consoleMessage);
});

I think you are trying something like
var commands = {
hide: 'hide()',
hideBg: 'hide(background)'
};
var codePrompt = prompt("Set the code in the command line."),
alertMessage;
switch (codePrompt) {
case commands.hide:
alertMessage = "Hiding elements...";
break;
case commands.hideBg:
alertMessage = "Hiding Background...";
break;
default:
alertMessage = "WRONG command";
break;
}
}
However, you can also use
var commands = {
'hide()': "Hiding elements...",
'hide(background)': "Hiding Background..."
};
var codePrompt = prompt("Set the code in the command line.");
var alertMessage = commands[codePrompt] || "WRONG command";
I guess you also want to run some functions:
var commands = {
'hide()': {
text: "Hiding elements...",
funcion: someFunctionToHide
},
'hide(background)': {
text: "Hiding Background...",
funcion: someFunctionToHideBackground
}
};
var codePrompt = prompt("Set the code in the command line."),
command = commands[codePrompt];
if(!command) {
alertMessage = "WRONG command";
} else {
alertMessage = command.text;
command.function();
}

switch operates by comparing the value being switched on to each of the possible cases using the identity operator ===. This means that you can put an array inside a case, and it will work as specified (but certainly not very intuitively for arrays):
var x = [1];
var a = [1];
switch (x) {
case [1]: alert("it's [1]!"); break;
case a: alert("it's a!"); break;
case x: alert("it's x!"); break;
}
This will alert "it's x!", while you might be expecting that either of the preceding two cases would be "good enough" to trigger. But that's just how === works:
[1] === x // false
a === x // true
x === x // true
So while you can technically use an array, in practice it would be very unusual to have a situation where it's actually useful to do so.
Going back to your code, since the values you are interested in are strings it seems that using a simple object as a map would do just fine:
var commands = {
"hide()": {
alert: "Hiding elements...",
console: "Blah blah"
}.
"hide(background)": {
alert: "Hiding background...",
console: "Blah blah"
}.
};
var fallback = {
alert: "Sorry, wrong command",
console: "Sorry, wrong command"
};
which would then allow you to write
var result = commands[input] || fallback;
alert(result.alert);
console.log(result.console);

Related

Using switch case in javascript

This is the variable i am having right now
[
{
"_id":"63773059c3160f782c087e33",
"nfrid":"637328ebf5c4b2558b064809",
"nfrname":"azuread",
"fileName":"package.json",
"isImport":false,
"isConst":false,
"isComponent":false,
"isNewFile":false,
"landmark":"\"react\"",
"isAfter":false,
"fileContent":"\"#azure/msal-react\": \"^1.4.9\",",
"filePath":"package.json",
"isPackage":true,
"isIndexHtml":false,
"projecttypeid":"6372366d1b568e00d8af2e44",
"projecttypetitle":"PWA React",
"nfrGitIo":[
{
"_id":"637328ebf5c4b2558b064809",
"iconpath":"https://cdnerapidxdevportal.azureedge.net/webdesignerimages/azure-active-directory-aad-icon-488x512-3d71nrtk.png",
"title":"Azure AD",
"description":"Azure Active Directory (Azure AD), part of Microsoft Entra, is an enterprise identity service that provides single sign-on, multifactor authentication, and conditional access to guard against 99.9 percent of cybersecurity attacks."
}
]
},
{
"_id":"63773144c3160f782c087e35",
"nfrid":"637328ebf5c4b2558b064809",
"nfrname":"azuread",
"fileName":"index.js",
"isImport":true,
"isConst":false,
"isComponent":false,
"isNewFile":false,
"isPackage":false,
"landmark":null,
"isAfter":null,
"fileContent":"import { MsalProvider } from '#azure/msal-react';import { msalConfig } from './authConfig';import {PublicClientApplication } from '#azure/msal-browser';",
"filePath":"src/index.js",
"isIndexHtml":false,
"projecttypeid":"6372366d1b568e00d8af2e44",
"projecttypetitle":"PWA React",
"nfrGitIo":[
{
"_id":"637328ebf5c4b2558b064809",
"iconpath":"https://cdnerapidxdevportal.azureedge.net/webdesignerimages/azure-active-directory-aad-icon-488x512-3d71nrtk.png",
"title":"Azure AD",
"description":"Azure Active Directory (Azure AD), part of Microsoft Entra, is an enterprise identity service that provides single sign-on, multifactor authentication, and conditional access to guard against 99.9 percent of cybersecurity attacks."
}
]
},
]
I am having many flags like isImport, isPackage, isIndexHtml like that. I am trying to put those flags in a switch case and call individual function when each flag is true.Something like this,
for (let i = 0; i < cosmos.length; i++) {
console.log(cosmos[0].isPackage);
switch (cosmos[i]) {
case `${cosmos[i].isImport === true}`:
const statusImport = common.updateImport(cosmos[i]);
console.log(statusImport);
break;
// case `${cosmos[i].isConst === true}`:
// console.log("I own a dog");
// break;
case `${cosmos[i].isPackage === true}`:
const statusPackage = common.updatePackage(cosmos[i]);
console.log(statusPackage);
break;
case `${cosmos[i].isIndexHtml === true}`:
const statusIndexHtml = common.updateIndexHTML(cosmos[i]);
console.log(statusIndexHtml);
break;
// case `${cosmos[i].isNewFile === true}`:
// const statusNewFile = common.addNewFile(cosmos[i]);
// console.log(statusNewFile);
// break;
default:
console.log("Nothing to add/update");
break;
}
}
But when I run this i am always getting the default console log. I dont know what i am missing
This is my first switch case implementation. Can someone point me in the right direction?
Don't convert them to strings and in switch condition add just true:
for (let i = 0; i < cosmos.length; i++) {
console.log(cosmos[0].isPackage);
switch (true) {
case cosmos[i].isImport:
const statusImport = common.updateImport(cosmos[i]);
console.log(statusImport);
break;
case cosmos[i].isPackage:
const statusPackage = common.updatePackage(cosmos[i]);
console.log(statusPackage);
break;
case cosmos[i].isIndexHtml:
const statusIndexHtml = common.updateIndexHTML(cosmos[i]);
console.log(statusIndexHtml);
break;
default:
console.log("Nothing to add/update");
break;
}
}
switch is not the right construct to use in this case.
Simply use if/else here.
Since you're testing several different values from cosmos[i], not testing a single value against multiple possible matches, switch isn't the right tool here. (You can use it, just like you can use a wrench to bang in a nail, but it's not the right tool.) Instead, use an if/else if/else chain:
for (let i = 0; i < cosmos.length; i++) {
if (cosmos[i].isImport) {
const statusImport = common.updateImport(cosmos[i]);
console.log(statusImport);
} else if (cosmos[i].isPackage) {
const statusPackage = common.updatePackage(cosmos[i]);
console.log(statusPackage);
} else if (cosmos[i].isIndexHtml) {
const statusIndexHtml = common.updateIndexHTML(cosmos[i]);
console.log(statusIndexHtml);
} else {
console.log("Nothing to add/update");
}
}
Separately, in new code, I'd suggest using a for-of instead of a for when you don't need the index:
for (const entry of cosmos) {
if (entry.isImport) {
const statusImport = common.updateImport(entry);
console.log(statusImport);
} else if (entry.isPackage) {
const statusPackage = common.updatePackage(entry);
console.log(statusPackage);
} else if (entry.isIndexHtml) {
const statusIndexHtml = common.updateIndexHTML(entry);
console.log(statusIndexHtml);
} else {
console.log("Nothing to add/update");
}
}
A switch statement can only interrogate one variable. In your case the correct solution is an if statement for each member variable. Replace the switch statement with this snippet:
if (cosmos[i].isImport === true) {
const statusImport = common.updateImport(cosmos[i]);
console.log(statusImport);
}
if (cosmos[i].isPackage === true) {
const statusPackage = common.updatePackage(cosmos[i]);
console.log(statusPackage);
}
if (cosmos[i].isIndexHtml === true) {
const statusIndexHtml = common.updateIndexHTML(cosmos[i]);
console.log(statusIndexHtml);
}
I note that your data structure does not mutually exclude the isImport isPackage and isIndexHtml - so in principle any combination of them could be true and my proposed code would execute accordingly.

How to return if condition from Google's AdminDirectory

I'm trying to return different results for respective google workspace users, the problem I'm facing is... the first answer is returning all users.
E.g. William Tell and John Peter gets the return of Mark Thomas i.e. www.google.com
Expectation: I want to display the answer for respective users.
Where did I go wrong?
function getUserID() {
var user = Session.getActiveUser().getEmail();
var name = AdminDirectory.Users.get(user).name.fullName;
if (name ="Mark Thomas") {
greeting= "www.google.com";
} else if (name ="William Tell"){
greeting = "www.msn.com";
}
} else if (name ="John Peter"){
greeting = "www.yahoo.com";
}
return greeting;
}
Findings:
You need to initialize the variable named greeting on your script.
You have an extra unnecessary closing bracket on the line before else if (name ="John Peter")
statement.
You may test this tweaked script below:
Modified script:
function getUserID() {
var user = Session.getActiveUser().getEmail();
var name = AdminDirectory.Users.get(user).name.fullName;
var greeting; //"greeting" needs to be initialized for the script to work
if(name == "Mark Thomas") {
greeting= "www.google.com";
} else if (name == "William Tell"){
greeting = "www.msn.com";
} else if (name == "John Peter"){
greeting = "www.yahoo.com";
}
return greeting;
}
Test Result:
Suggestion:
Alternatively, I suggest you use a Switch statement since you have multiple fixed conditions instead of a nested If-Else statement. A switch statement is usually more efficient than a set of nested ifs.
Script w/ Switch statement:
function getUserID() {
var user = Session.getActiveUser().getEmail();
var name = AdminDirectory.Users.get(user).name.fullName.toString();
var greeting; //"greeting" needs to be initialized to exist & be used on the script
switch(name){
case name = "Mark Thomas":
greeting = "www.google.com";
break;
case name = "William Tell":
greeting = "www.msn.com";
break;
case name = "Admin IJG": //Added my test account's full name to see if it works
greeting = "www.yahoo.com";
break;
}
return greeting;
}
Sample Test Result:
name ="Mark Thomas" is an assignment not a test for equivalency.
try name == "Mark Thomas"

function inside an object

I have a function inside an object but it isn't executed. Where did I go wrong.
JS:
switch(sometext){
case "GetStatus":
AgentReply = {
IsCustomer: false,
//UserText:"in process"
UserText: function () {
alert("test");
var text = "";
switch ($scope.LanguageId) {
case "1":
text = "is in process";
break;
case "2":
text = "test message";
break;
}
return text;
}
}
break;
}
This code was working fine. But now I have conditions for 'UserText'. So, commented the original code and wrote a function to get the desired message for 'UserText'. But the alert never pops up.
You should execute function, add () after }, like so
UserText: function() {
alert("test");
var text = "";
switch ($scope.LanguageId) {
case "1":
text = "is in process";
break;
case "2":
text = "test message";
break;
}
return text;
}()

How to insert an if in a switch case in javascript?

I have this simple javascript function:
function updateDeleteUser(action, userid) {
frm = document.getElementById("frmsearch");
frm.frmUserId.value = userid;
switch (action) {
case 0:
frm.action = "UpdateUser.jsp";
break;
case 1:
confirm("Delete account?");
if (confirm != false){
frm.action = "DeleteUser.jsp";
}
}
frm.submit();
}
Even if I click on 'NO' the function runs anyway and user gets deleted. What did I do wrong?
Thanks in advance.
You are not doing anything with the return value of the confirm(…) call, instead you use the confirm function itself as the compare value in your if-condition. You want
if (confirm("Delete account?")) {
frm.action = "DeleteUser.jsp";
}
Notice that this has nothing to do with the switch statement.
You are using Confirm Method is wrong position as it always behaves like native function.#
Correct usage is as follows
case 1:
// confirm("Delete account?");
if (confirm("Delete account?") != false){
frm.action = "DeleteUser.jsp";
}

Changing an image in a switch statement

I have an image in my HTML, but i would like to change the image when an answer is given by the user. For some reason the first function works, but the image doesn't change.. Can someone help me please.
This is my code so far:
window.onload = function () {
'use strict';
var showMessage = function (text) {
var messageCenter = document.getElementById('messageCenter');
messageCenter.innerHTML += "<p>" + text + "</p>\n";
};
var checkName = function (name) {
switch (prompt("What is your name?")) {
case "Leonard":
showMessage("Leonard! How did I not recognize you! Why would you like to get rid of me!");
break;
case "Penny":
showMessage("Penny Penny Penny! You've got so much to learn.");
break;
case "Howard":
showMessage("Howard, the only one without a Ph.D");
break;
case "Raj":
showMessage("Interesting. You're afraid of insects and women. Ladybugs must render you catatonic!");
break;
default:
showMessage("Well, I'm not familiair with you. I don't like to talk to strange people.");
break;
}
};
checkName()
var myImage = document.getElementById('sheldon');
var checkCase = function (img) {
switch (img) {
case "Leonard":
myImage("verbaasd.jpg");
break;
case "Penny":
myImage("les.jpg");
break;
case "Howard":
myImage("howard.jpg");
break;
case "Raj":
myImage("loser.jpg");
break;
default:
myImage("sheldon.jpg");
break;
}
};
checkCase()
};
Your error is in myImage(). You set this variable with a DOM object and call it as a normal function. This gives you an error. You also forgot to store the name and pass it as argument to your checking functions.
Your code should be:
window.onload = function () {
'use strict';
var name = prompt("What is your name?");
var showMessage = function showMessage(text) {
var messageCenter = document.getElementById('messageCenter');
messageCenter.innerHTML += "<p>" + text + "</p>\n";
};
var checkName = function (name) {
switch (name) {
case "Leonard":
showMessage("Leonard! How did I not recognize you! Why would you like to get rid of me!");
break;
case "Penny":
showMessage("Penny Penny Penny! You've got so much to learn.");
break;
case "Howard":
showMessage("Howard, the only one without a Ph.D");
break;
case "Raj":
showMessage("Interesting. You're afraid of insects and women. Ladybugs must render you catatonic!");
break;
default:
showMessage("Well, I'm not familiair with you. I don't like to talk to strange people.");
break;
}
};
checkName(name);
var myImage = function myImage(img) {
var sheldon = document.getElementById('sheldon');
sheldon.innerHTML = '<img src="' + img + '"/>';
};
var checkCase = function (name) {
switch (name) {
case "Leonard":
myImage("verbaasd.jpg");
break;
case "Penny":
myImage("les.jpg");
break;
case "Howard":
myImage("howard.jpg");
break;
case "Raj":
myImage("loser.jpg");
break;
default:
myImage("sheldon.jpg");
break;
}
};
checkCase(name);
};
Now your myImage() is a function which insert a new image inside a container with ID sheldon.
If you don't want to have a container for the image, and instead you want reference directly to the image, can change the myImage() function in:
var myImage = function myImage(img) {
var sheldon = document.getElementById('sheldon');
sheldon.src = img;
};
BTW, I see that you're learning so it's right to start from the basics, but remember that there are cleaner ways to do that.
Hope it's helpful to you.

Categories

Resources