javascript retrieve value from a map - javascript

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')
}

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.

traverse array of objects and show image according to a type

I have an array of objects in a state in pinia, I get this array in my component. I am trying to show an image or others according to a value that is in the object, I make a function where I go through the array here and using switch I check the type, and return the image that corresponds to the type, I do this but I only get returns the first image if I use a for, if I do it with forEach it returns null, I try to save the value in the function because it is the one that I command to call to show the image, how can I do this so that according to a type I show a different image?
Function where you tried to get the images
const imgSelect = () => {
for(let i = 0; i < obj.value.length; i++){
switch(obj.value[i].type){
case 'one':
return new URL('../assets/images/image1.png', import.meta.url).href
break;
case 'two':
return new URL('../assets/images/image2.png', import.meta.url).href
break;
case 'three':
return new URL('../assets/images/image3.png', import.meta.url).href
break;
default:
return null
break;
}
}
}
here I try to use the image, it is to show it on a map as a markup and show one image or another depending on the type
const imageMarker = imgSelect
As commented
You will have to use Array.map
You are only getting 1 image because you are using a return in for loop. So you return on 1st iteration and remaining iterations never gets evaluated
Sample:
const getUrl = (type) => {
switch (type) {
case 'one':
return new URL('../assets/images/image1.png',
import.meta.url).href
break;
case 'two':
return new URL('../assets/images/image2.png',
import.meta.url).href
break;
case 'three':
return new URL('../assets/images/image3.png',
import.meta.url).href
break;
default:
return null
break;
}
}
const imgSelect = () => {
obj.value = obj.value.map(
(item) => ({...item, url: getUrl(item.type)})
)
}
If you have predefined list of images based on type, you can even create a predefined map and fetch from that. No need to create for every iteration.
const URL_TYPE_MAP = {
one: new URL('../assets/images/image1.png', import.meta.url).href,
two: new URL('../assets/images/image2.png', import.meta.url).href,
three: new URL('../assets/images/image3.png', import.meta.url).href,
}
const getUrl = (type) => {
return URL_TYPE_MAP[type]
}

Calling a function within a for loop - JavaScirpt

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/

Convert ternary to if/else in mapped array function

I have a ternary within a map function, that currently only switches based on one option. I need to be able to pull the "home" option and set it to "/" if the user clicks that option
const buttons = ['Home', 'Docs', 'About-Us'];
const buttonSlugs = buttons.map(button => button === 'About-Us' ? 'aboutus' : button.toLowerCase());
How can I modify the ternary to an if/else, so that the home button can be set to "/"?
You can use a conditional like:
const buttons = ['Home', 'Docs', 'About-Us'];
const buttonSlugs = buttons.map(button => {
if (button === 'About-Us') {
return 'aboutus';
}
else if (button === 'Home') {
return '/';
}
else {
return button.toLowerCase();
}
});
console.log(buttonSlugs);
But this sort of approach can get ugly if you have many mappings or if you expect to add more. Another approach is to use an object of functions, each of which performs the transformation you wish for a given button:
const buttons = ['Home', 'Docs', 'About-Us'];
const transformations = {
'About-Us': () => 'aboutus',
Home: () => '/',
Docs: button => button.toLowerCase(),
};
const buttonSlugs = buttons.map(btn => transformations[btn](btn));
console.log(buttonSlugs);
This is easily extensible and keeps the transformation logic out of the map.
If you want a default action or the ability to handle missing buttons, you can check for an empty key in the transformations object before calling the retrieved function and proceed accordingly.
Are you just asking for:
buttons.map(button => {
if(button === 'Home'){
do something
} else if (button === 'About-us') {
do something else
} else if (button === 'Docs') {
do something elser
}
}
might be better to use a switch though and a forEach since map returns something, forEach doesnt:
buttons.forEach(button => {
switch(button){
case 'Home':
do something
break
case 'About-us':
do something
break
case 'Docs':
do something
break
default:
break
}
}
You could use a switch statement rather than if
const buttonSlugs = buttons.map(button => {
switch (button) {
case 'About-Us':
button = 'aboutus';
break;
case 'Docs':
button = 'docs';
break;
case 'Home':
button = '/';
break;
}
})
I think this is what you wanted to do.
const buttons = ['Home', 'Docs', 'About-Us'];
const buttonSlugs = buttons.map((button)=>{
if(button==='About-Us'){
return 'aboutus';
}
else if(button==='Home'){
return '/';
}
else{
return button.toLowerCase();
}
});
console.log(buttonSlugs); // for result
const buttons = ['Home', 'Docs', 'About-Us'];
const buttonSlugs = buttons.map(button => {
let slug;
switch (button) {
case 'About-Us':
slug = 'aboutus';
break;
case 'Home':
slug = '/';
break;
default:
slug = button.toLocaleLowerCase();
break;
}
return slug;
});

How to match a template string in switch statement with js?

I have a function that returns a component that depends on the pathname of the window.
getComponentByPathname = (pathname) => {
switch(patname){
case "/view1": return <ViewOneComponent>;
case "/view2": return <ViewTwoComponent>;
}
But the problem starts when I try to evaluate a template string that has one id
getComponentByPathname = (pathname) => {
switch(pathname){
case "/view1": return <ViewOneComponent>;
case "/view2": return <ViewTwoComponent>;
case `/view3/${getId()}`: return <ViewThreeComponent>;
}
It's only working with the first two cases. Why?
Also, I make another attempt. In this case, I literally paste the string with the Id in the third case, like this:
case "view3/1234567": return <ViewThreeComponent>;
And works. But the problem is that I can not hardcode the id in the string.
How I can evaluate that?
My guess would be that getId() is returning a different value then what you expect. I would try the following and make that getId() is returning the expected value when it is being calculated
getComponentByPathname = pathname => {
const case3 = `/view3/${getId()}`;
console.log(`case3 = ${case3}`);
console.log(`pathname = ${pathname}`);
switch (pathname) {
case '/view1':
return <ViewOneComponent>;
case '/view2':
return <ViewTwoComponent>;
case case3:
return <ViewThreeComponent>;
}
};
But if you only need to decide which component to render based on your path then something like this might be more appropriate
const examplePaths = ['view1/', 'view2/', 'view3/', 'view3/1241232', 'view3/8721873216', 'view4/', 'vi/ew1', ''];
const mapper = {
view1: 'ViewOneComponent',
view2: 'ViewTwoComponent',
view3: 'ViewThreeComponent'
};
examplePaths.forEach(ent => {
const splitPaths = ent.split('/');
const mapped = mapper[splitPaths[0]];
if (mapped) {
console.log(mapped);
} else {
console.log('Path not supported');
}
});
Works fine here
function getId() {
return 1234567
}
function test(pathname) {
switch (pathname) {
case '/view1':
return 'ViewOneComponent'
case '/view2':
return 'ViewTwoComponent'
case `/view3/${getId()}`:
return 'ViewThreeComponent'
default:
return 'fail'
}
}
console.log(test('/view3/1234567'))

Categories

Resources