Calling a function within a for loop - JavaScirpt - javascript

Hi I am trying to call a function within a for loop but It isn't working...This is how my code currently looks like:
bot.on('message', data => {
if (data.type !== 'message' || data.subtype === 'bot_message') {
return;
}
findClassroomMention(data,text);
});
var classrooms =
{
L108: ["lokaal 108","L108","108"],
L208: ["lokaal 208","L208","208"]
};
function findClassroomMention(message) {
var found = false
for(var ClassroomId in classrooms) {
for(var term of classrooms[ClassroomId]) {
if(message.includes(term)) {
found = ClassroomId;
notifyProblemSolver();
break;
}
}
if (found) notifyProblemSolver(); break;
}
return found
};
function notifyProblemSolver(ClassroomId) {
const params = {
icon_emoji: ':smiley:'
}
bot.postMessageToChannel('caris','We have a problem in' + ClassroomId, params);
};
I want the function notifyProblemSolver() to be called in the for loop...But if I run the code it isn't working. Any tips? Thanks in advance!

I think if (found) notifyProblemSolver; break; is the issue. That break will be called regardless of if (found) so for(var ClassroomId in classrooms) { will only run once.
I think you meant
if (found) {
notifyProblemSolver();
break;
}

I've seen some unnecessary semicolons at the end of functions. Also the part:
if (found) notifyProblemSolver; break;
Should be replaced with:
if (found) notifyProblemSolver(); break;
Because you are calling a function here, instead it was an expression.
Let me know if this works.
Full code modification here:
https://jsfiddle.net/terza_terza/ms9xLrzu/3/

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.

javascript retrieve value from a map

I am trying to develop a google script app.
Here is one function to create an array map.
function getOffices(){
var result=AdminDirectory.Groups.list({domain:"example.com"})
result=result.groups.filter(function(group){
var str=group.email;
return str.search("-office#example.com")>=0;
})
result=result.map(function(group){ return {name:group.name,email:group.email}})
return result;
}
I have created a logic piece, that I want to execute certain actions based on the results, that looks like this:
var getOrgUnitPath = (accountOffice, accountType) => {
if (accountType === 'facilitator') {
return 'Limited Accounts/Gmail Plus Calendar';
} else {
switch (accountOffice) {
case accountOffice.includes('Boston'):
return "/Standard-Access/Boston";
break;
case accountOffice.includes('New York'):
return '/Standard-Access/New York';
break;
case accountOffice.includes('Lincoln'):
return '/Standard-Access/Lincoln';
break;
default:
return '/Standard-Access';
break;
}
}
};
Lastly, I try to set the organizational unit -- which is ultimately what i am trying to do, but can't seem to get the syntax right, I have tried everything I can think of. I have hardcoded the "accountType" and it worked, so I know the formObject.accountType is functioning properly.
orgUnitPath: getOrgUnitPath(accountType, formObject.accountType),
Thanks in advance!
This is a wrong usage of switch case.
if accountOffice's would be just New York, Boston, Lincoln. Remove the complex condition and replace with
switch (accountOffice) {
case "Boston":
return "/Standard-Access/Boston";
break;
case "New York":
return "/Standard-Access/New York";
break;
case "Lincoln":
return "/Standard-Access/Lincoln";
break;
default:
return "/Standard-Access";
break;
}
If not, use if-else if you have complex condition to check rather than simple match cases
if (accountOffice.includes("Boston")) {
return "/Standard-Access/Boston";
} else if (accountOffice.includes("New York")) {
return "/Standard-Access/New York";
} else if (accountOffice.includes("Lincoln")) {
return "/Standard-Access/Lincoln";
} else {
return "/Standard-Access";
}
I rewrote the code so I could get a better understanding of it. From what I can tell, getOffices lists all offices and getOrgUnitPath returns a path including the first office that matches the ordered list of offices ['Boston', 'NY', 'Lincoln']. If that's the case, what's missing is that the first argument to getOrgUnitPath should be getOffices(), right? (Notice it is the execution of the function getOffices.)
Here's the code "simplified" to my liking. I hope it helps:
const getOffices = () => {
const bigList = x.y.list({ domain: 'example.com' }) // ?
return bigList
.filter(cur => ~cur.email.search('abc'))
.map(cur => ({
name: cur.name,
email: cur.email
}))
}
const getPath = (accOffice, accType) => {
if (accType === 'xyz')
return 'foobar'
const city = ['Boston', 'NY', 'Lincoln']
.find(cur => accOffice.includes(cur))
return `yadayada/${city}`
}
const theFinalObj = {
orgUnitPath: getPath(getOffices(), 'rightHardcodedType')
}

Text undefined - JavaScript

I'm currently making a chatbot for a school project.
So basically what I want is for the chatbot to send a copy of a certain message from the user's input to another channel. But when I run my code it returns the value as undefined. My code looks like the following:
bot.on('message', data => {
if (data.type !== 'message' || data.subtype === 'bot_message') {
return;
}
findClassroomMention(data.text);
});
var classrooms =
{
L108: ["L108","108"],
L208: ["L208","208"]
};
function findClassroomMention(message) {
var found = false
for(var ClassroomId in classrooms) {
for(var term of classrooms[ClassroomId]) {
if(message.includes(term)) {
found = ClassroomId;
break;
}
}
if (found) {
notifyProblemSolver();
break;
}
}
return found
};
function notifyProblemSolver(ClassroomId) {
const params = {
icon_emoji: ':smiley:'
}
bot.postMessageToChannel('caris','We have a problem in ' + ClassroomId, params);
};
For example the user's input is:
Hi I have a problem in classroom L108
Then I want the chatbot to send a message to the problemsolver containing the value L108, like this:
We have a problem in L108
But when I run the code it sends L108 as undefined:
We have a problem in undefined
You forgot to pass the ClassroomId in notifyProblemSolver()
Problem
if (found) {
// You forgot to pass the ClassroomId
notifyProblemSolver();
break;
}
Solution
if (found) {
// Add the ClassroomId
notifyProblemSolver(ClassroomId);
break;
}
from what I can see, notifyProblemSolver function is only called in
if (found) {
notifyProblemSolver();
break;
}
If you don't pass any arguments to the function call it, your ClassroomId parameter will be undefined in that specific call. I think what you meant to do was pass found to it like:
if (found) {
notifyProblemSolver(found);
break;
}

Javascript - For Loop not finding values in array correctly

I have an array with a list of customers. I am declaring a function that takes a customer name as a parameter. I want this function to loop through the array to find out whether or not the customer is in the array.
var customers = [
{fullName: 'Marshall Hathers',
dob: '01/07/1970'},
{fullName: 'Margaret May',
dob: '01/07/1980'}
];
The function:
function findCustomer(customer) {
for(i=0; i<customers.length; i++) {
var found;
if(customer === customers[i].fullName) {
found = true;
console.log('Customer has been found');
break;
} else {
found = false;
console.log('Customer has not been found');
break;
}
}
It works well the first time a customer is found, but it prints out incorrectly when trying to find the second customer.
Can anyone please assist?
So look at what you're actually saying in your loop. The loop body will run for each customer. So you're saying
For the first customer in the array
if this is my customer
print "found" and stop looping
otherwise
print "not found" and stop looping
Does that look right to you? Does looking at the first record alone really tell you that the customer isn't found?
And note that since all possibilities end with "and stop looping" the 2nd record is never examined. The whole point of a loop is that in at least some condition, you don't stop looping, right? So that you would then see the step repeated for the 2nd, and so on...
Omit the else part and break the for loop if found.
function findCustomer(customer) {
var found, i;
for (i = 0; i < customers.length; i++) {
if (customer === customers[i].fullName) {
found = true;
console.log('Customer has been found');
break;
}
}
if (!found) {
console.log('Customer has not been found');
}
}
Use the Array.some prototype function to find the element
function findCustomer(customer) {
var found = customers.some(function(item) {return item.fullName == customer;});
console.log(found ? 'Customer has been found': 'Customer has not been found');
}
You are exiting the loop when your script reach to a break
So if you look for the second customer, you will enter in the "else". And there you have got a break that exit from the loop, so you will never get the console.log
Just remove the break; statement from the else block;
Here I rewritten the function for you.
function findCustomer(customer) {
var found = false;
for(i=0; i<customers.length; i++) {
if(customer === customers[i].fullName) {
found = true;
break;
} else {
found = false;
}
}
if(found){
console.log('Customer has been found');
}else{
console.log('Customer has not been found');
}
}
I would change the code like this (edited as suggested in comment)
var customers = [{
fullName: 'Marshall Hathers',
dob: '01/07/1970'
}, {
fullName: 'Margaret May',
dob: '01/07/1980'
}];
function findCustomer(customer) {
for (i = 0; i < customers.length; i++) {
if (customer === customers[i].fullName) {
console.log('Customer has been found');
return true;
}
}
console.log('Customer has not been found');
return false;
}
findCustomer('Marshall Haters');

Function parameter not carried to switch statement in JavaScript

I've been making a basic game but I've encountered a problem while trying to make a function that would be usable among several occasions by using the switch statement. The output I keep getting when I run the function is the default code block. Here's some sample code:
function battle(boss) {
slaying = true;
while(slaying) {
switch(boss) {
case 'boss1':
console.log('This is' + boss1.name);
break;
case 'boss2':
console.log('This is' + boss2.name);
break;
default:
console.log('No boss');
break;
}
slaying = false;
}
}
function Boss(name) {
this.name = name;
}
var boss1 = new Boss('boss1');
var boss2 = new Boss('boss2');
battle(boss1);

Categories

Resources