Using object literals for my complex cases - javascript

Hey I was wondering if it is somehow possible to use a object literal in this case to clean up my switch statement.
export const getTravelInfo = () => {
const url = window.location.href;
switch (url as any) {
case url.includes('trips'):
return epicTrips;
case url.includes('mini-trips'):
return miniTrips;
case url.includes('sailing-trips'):
return sailingTrips;
default:
return epicTrips;
}
};
This is what I have so far, I am just not sure how or even if this is possible to pass in a function and loop over the url to determine what string is present in the url and then deliver that value to the user.
function getTravelInfo2 () {
const url = window.location.href;
var travel = {
'trips': epicTrips,
'mini-trips': miniTrips,
'sailing-trips': sailingTrips,
'default': epicTrips
};
return travel[url];
}

My solution was to First get what I need from the URL Via
const url = 'http://www.test.com/trips';
firstPart = url.split('/', -1)[-1];
getTravelInfo(firstPart);
const getTravelInfo = (type) => {
var travel = {
'trips': epicTrips,
'mini-trips': miniTrips,
'sailing-trips': sailingTrips,
'default': epicTrips
};
return (travel[type] || travel['default']);
}
Much cleaner and easier to execute and understand.

Related

how can I use a variable value to define a new variable in JavaScript? [duplicate]

This question already has an answer here:
using variable results (contents) to create new variables
(1 answer)
Closed 10 months ago.
I have a list
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
how can I use these peoples numbers if their names matches another variable result?
We have
var name = *selected server-side student names*
and by these * signs I mean it's a great list that name gives up but it only gives up one name out of that list at the time we call it.
If one of these students is selected by name variable, how can I use the number defined in front of that name in const StudentCode to generate a url?
Suppose you get Rose! Then the number for Rose is: 35621548 and the url for example will be https://www.35621548.com. What code can we use to generate this url for example in console?
console.log(url)
Use this:
if (StudentCode.hasOwnProperty(name){
const url = `https://www.${StudentCode[name]}.com`
}
This function will return you the url on the basis of the student name that is passed in this function.
function returnURL(studentName){
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
if (!!!StudentCode[studentName]) return "";
return "https://" + StudentCode[studentName] + ".com";
}
console.log(returnURL("Rose"));
Hope, this helps!!
const StudentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
let studentName = "Jack"
const url = `https://${StudentCode[studentName]}.com`
console.log(url)
export const studentUrlModule = (function() {
const studentCode = {
Jack: 32658495,
Rose: 35621548,
Lita: 63259547,
Seth: 27956431,
Cathy: 75821456,
};
const url = 'https://$code.com'
const generateUrl = function(code = '') {
if (!url) {
throw new Error('Url is not defined')
} else if (!code) {
throw new Error('Code is not defined')
};
return url.replace('$code', `${code}`);
}
function getCode(name = '') {
const code = studentCode[name];
if (!code) {
throw new Error(`There is no code with name(${name}).`);
}
return code;
}
function getUrl(name = '') {
if (!name) {
throw new Error('StudentName is undefined')
};
const code = getCode(name);
const studentUrl = generateUrl(code);
return studentUrl;
}
return {
generateUrl,
getCode,
getUrl,
};
}());
Maybe it helps. If the code was not founded then it throws an error. Please use try, catch error handlers to handle errors.
-- Update
I updated the code and as you can see it's a module and you need to import it everywhere you like to use this.
if you are not familiar with modules and how to use them inside the browser check documents.
Mozila documents
Super Simple Start to ESModules in the Browser

How can I extract path parameters from url?

Let's say I have an object that contains the values:
const pathParams = { schoolId :'12', classroomId: 'j3'}
and I have a path: school/:schoolId/classroom/:classroomId
I would like to extract: 'schoolId' and 'classroomId' from the path so that I can later replace them with their corresponding values from the pathParams object. Rather than iterating from the pathParam object keys, I want to do the other way around, check what keys the path needs and then check their values in the object.
I currently have this:
function addPathParams(path, paramsMap) {
const pathParamsRegex = /(:[a-zA-Z]+)/g;
const params = path.match(pathParamsRegex); // eg. school/:schoolId/classroom/:classroomId -> [':schoolId', ':classroomId']
console.log('--params--', params)
let url = path;
params.forEach((param) => {
const paramKey = param.substring(1); // remove ':'
url = addPathParam(url, param, paramsMap[paramKey]);
});
return url;
}
function addPathParam(path, param, value) {
return path.replace(`${param}`, value);
}
Does this look robust enough to you? Is there any other case I should be considering?
Here's a couple of tests I did:
Result:

Let statement in Explorer?

My project (with HTML and JavaScript) doesn't work in Internet Explorer and I think that is because I use a let statement in a JS method. Can I add some external libraries that makes it possible to read the let statements? Or can I rewrite the function? I don't really know how the let method works so can anyone tell me how to rewrite these lines:
initializeData = function()
{
//Check URL and QueryString
var url = window.location.href.toString();
var queryString = (url.split("?"))[1];
if (queryString == undefined || queryString=="" || queryString==null)
resetData();
else //filter data based on URL QueryString
{
const query = decodeURI(queryString);
const result = query.split('&');
result.forEach(function(item){
const [cat, values] = item.split('='); //ERROR
const isArray = cat.endsWith('[]');
let pair;
if (isArray)
{
const p = values;
pair = { cat, 'values': [values] };
}
else
{
pair = {cat, values };
}
currentFilters.push(pair);
});
RunFilter();
}
}
I need pair to be on the same structure since I am using it in the RunFilter() method.

Instantiating a new function no access to inner function

This is quite a frustrating issue I am stuck on. I am exporting a parent function with quite a rigid structure for the purpose of library mocking.
const responses = require("../responses/index.js");
function fetch (
first = "contactsMultiple",
second = "passwordFail",
third = "contactsMultiple") {
this.first = first;
this.second = second;
this.third = third;
this.iteration = 1;
this.fetch = () => {
let body;
switch (this.iteration) {
case 1 :
body = responses.contacts[this.first];
break;
case 2 :
body = responses.password[this.second];
break;
case 3 :
body = responses.contacts[this.third];
break;
default:
body = responses.contacts["contactsMultiple"];
break;
}
const response = {
status: 200,
statusText: "OK",
json: () => {
return body;
}
};
this.iteration++;
return response;
}}
module.exports = fetch;
I export this, then import it, create a new instance of the function so I can set properties that I wish to increment and also set via the construction of the function. But the code then expects a function called fetch.
I need to be able to call it like:
const Fetch = new fetch();
then pass Fetch into the existing classes.
If I log this new function I can see it has a fetch property of a type function. but I keep getting this.fetch is not a function.
What am I missing?
Many thanks

Dynamically create a links from an array of items

I need to create a ul of links based on the valued in an array. The links are created but the href attribute is being randomly assigned and doesn't correspond to the actual value I'm passing in to my getUrl function.
Here is my code so far:
getURL (type) {
let url
switch (type) {
case 'Yahoo':
url = 'https://www.yahoo.com/'
case 'Bing':
url = 'https://www.bing.com/'
default:
url = 'https://www.google.com'
}
return url
}
and the render:
render () {
let { expandList } = this.state
let listItems = [
'Google',
'Bing',
'Yahoo'
]
let list = expandList
? listItems.map((item, index) => {
return (
<li key={index}>
<a href={this.getURL(item)} target='_blank'>
{item}
</a>
</li>
)
})
: ''
return (
<div>
<ul>{list}</ul>
</div>
)
}
You need to break after each case or return from it. If you don't it will always continue to default, and return the google url.
function getURL(type) {
switch (type) {
case 'Yahoo':
return 'https://www.yahoo.com/'
case 'Bing':
return 'https://www.bing.com/'
default:
return 'https://www.google.com'
}
}
console.log(getURL('Yahoo'));
console.log(getURL('Bing'));
switch basically tries to match type with the argument to the case, and when there's a match, it will execute the codes in all the cases below it unless you explicitly break it.
default is a catch-all in case none of the cases match the type.
The correct way to do it with switch would be breaking out of it after the case statement is executed. One way of doing this is by inserting break:
getURL (type) {
let url
switch (type) {
case 'Yahoo':
url = 'https://www.yahoo.com/'
break
case 'Bing':
url = 'https://www.bing.com/'
break
default:
url = 'https://www.google.com'
}
return url
}
You can also definitely return the url in the case statement as Ori Drori suggested, which will not only break out of the switch, but also break out of the function.
I would also recommend ending your statements with a semicolon. Even though it's optional, it can prevent unexpected errors.
Also, I would recommend lowercasing type with type.tolowercase() and match it with lowercase strings.
If all getURL does is to map the name of the website to the url, an alternative with less code would be using an object:
var nameToUrlMap = {
'yahoo': 'https://www.yahoo.com/',
'bing': 'https://www.bing.com/',
};
and then use it like:
var type = 'Yahoo';
var lowercasedType = type.tolowercase();
var url = nameToUrlMap[lowercasedType] || 'https://www.google.com/'; // falls back to google if name doesn't exist in nameToUrlMap
console.log(url); // "https://www.yahoo.com/"
console.log(nameToUrlMap['abcd'] || 'https://www.google.com/'); // "https://www.yahoo.com/"
You can wrap it in a function if you want:
var nameToUrlMap = {
'yahoo': 'https://www.yahoo.com/',
'bing': 'https://www.bing.com/',
};
function getURL(type) {
var lowercasedType = type.tolowercase();
var url = nameToUrlMap[lowercasedType] || 'https://www.google.com/'; // falls back to google if name doesn't exist in nameToUrlMap
}
You can use const or let in place of var as well.

Categories