Using Arithmetic operators in parameters of a Function - javascript

I tried to do it but didn't work
I want to achieve something like this:
function clubMember(clubName, women + men, women, men) {
const club = `${clubName} club has ${women + men} members including ${women} Women and ${men} Men`
return club
}

The answer is: no, you can't put arithmetic operators as a parameter.
As far as I know, there are no languages that gives you ability to calculate as a parameter.
However, you could do something like this if you wish:
function clubMember(clubName, total, women, men) {
const club = `${clubName} club has ${total} members including ${women} Women and ${men} Men`;
return club;
}
clubMember(club, women+men, women, men);

Related

I am trying to scrape amazon, and stop at a specific number

So this is my code
if (body.included != null && body.included.length > 0) {
let genres = '';
for(let i = 0; i < body.included.length; i++) {
genres += body.included[i].attributes.title;
if(i != body.included.length - 1) {genres += ', ';}
}
embed.addField('GENRES', [`${genres}`,], true);
}
this is the results whenever i search anything with this it gives me this:
Comedy, Kids, Fantasy, Fantasy World, Erotic Torture, Loli, Nudity, Bdsm, Bondage, Sex, Past, Plot Continuity, Violence, Military, Mecha, Historical, Action, Romance, Science Fiction, World War II, Japan, Asia, Piloted Robot, Alternative Past, Steampunk, Gunfights, Alien, War, Robot, Adventure, Space Travel, Cyborg, Crime, Other Planet, Humanoid Alien, Future, Space, Contemporary Fantasy, Vampire, Slice of Life, Detective, Bounty Hunter, Magic, Present, Demon, Super Power, Drama, Anime Influenced, Earth, Love Polygon, Angst, High School, School Life
Has this a example because other types searches comes with 1 or 2 or decent amount of genres where it doesn't have like 40 of them
like this one
Ninja, Fantasy World, Adventure, Action, Comedy, Martial Arts, Super Power, Romance, Disaster, Shounen, Love Polygon, Angst, Plot Continuity, Parallel Universe, Fantasy
So what i need help is how do i make it stop in a certain number where it wont give me 40 of them instead 10 or less
You could change the loop condition but still need to watch out for the length of the body.included array for cases where it has fewer than 10 elements. Try the following:
const MAX_GENRES = 10;
if (body.included && body.included.length) {
const max = Math.min(MAX_GENRES, body.included.length);
const genres = [];
let i = 0;
while (i < max) {
genres.push(body.included[i].attributes.title);
i += 1;
}
embed.addField('GENRES', [genres.join(',')], true);
}
This should achieve what you're after. I don't know the signature for embed.addField() but are you certain that the second argument should be a single-element array containing a string? Could be but seems weird. If the function calls for an array of strings use:
embed.addField('GENRES', genres, true);

Is creating instance of object same as creating object of same type?

I have to create an object, three instances of objects and arrays.
Create a cruise object that has the following properties:
Cruise Date,
Cruise Destination,
Cruise Description,
Cruise URL,
Ship Name,
Ship Description,
Ship URL,
Price
Make three instances of the cruise object.
Create an array of the three instances.
According to my understanding I created one cruise object with all properties mentioned and I have to create three more instances of object.
I did the following. Does creating instances means creating object of same type?
function Cruise(cruise_Date, cruise_Destination, cruise_URL, ship_Name, ship_Description, ship_url, price ) {
this.cruise_Date = cruise_Date;
this.cruise_Destination = cruise_Destination;
this.cruise_URL = cruise_URL;
this.ship_Name = ship_Name;
this.ship_Description = ship_Description;
this.ship_url = ship_url;
this.price = price
}
var myCruise = new cruise("16 March 2018",
'4 Night Bahmas cruise ',
"You know the name, the laid-back attitude and where to find them, but you’ll just have to visit The Bahamas to truly appreciate this classic cruise destination. On this 700-strong string of sun-splashed islands dotting the blue Atlantic, the living’s easy. (And it’s not bad on a Bahamas cruise either!) The central port of Nassau is the bustling capital of the country — bustling is a relative term, of course — while Freeport is all chill, all the time. And nothing is as delightfully desolate as Half Moon Cay and Princess Cays: pure private-destination paradise",
"https://www.ncl.com/cruise-destinations/bahamas-florida-cruises?cid=PS_TSI_CAL_DST_GOO-g_LEN_SRH_DESTBAF_3%20night%20bahamas%20cruise_NA_189086496943&kshid=998d4956-0345-4c42-88fb-0f1ce25bfbf9&kwid=659072&anchor=NA&gclid=Cj0KEQjw3rfOBRDJruDR8Ljm7e0BEiQAam-GsPAAXfpiBInuQfwSq6ZOe4U2KBmlRbc08kFl-gFJIBQaAtvn8P8HAQ",
'Majesty of the sea ', "MS Majesty of the Seas is a Sovereign-class cruise ship owned by Royal Caribbean Cruises Ltd and operated by Royal Caribbean International. ", "https://www.royalcaribbean.com/cruise-ships/majesty-of-the-seas",
'$' + 169);
var myCruise2 = new cruise("Cruise_Date", "Cruise_Destination", "Cruise_Description", "Cruise_URL", "Ship_Name", "Ship_Description", "Ship_URL", "Price");
var myCruise3 = new cruise("Cruise_Date", "Cruise_Destination", "Cruise_Description", "Cruise_URL", "Ship_Name", "Ship_Description", "Ship_URL", "Price");
list = new Array("Departs", "Destination", "Ship", "Price from");
instances = new Array(myCruise, myCruise2, myCruise3);
function displayList(the_date, ) {
// body...
}
expected output:
Your code in creating objects has a few problems. You would need to have an object constructor function named cruise() for that to work. Usually you capitalize object constructor functions. Also, I doubt they intended for you to give values of each property that are the same as the names of the properties. If you are giving an instance of an object of a cruise, you would give it an actual destination like "The Bahamas", etc. An object constructor function would look something like this:
function Cruise(date,destination,descr,url,name,price){
this.cruiseDate = date;
this.cruiseDestination = destination;
this.cruiseDescription = descr;
this.cruiseUrl = url;
this.cruiseName = name;
this.cruisePrice = price;
}
As for creating an array of objects, after you make the instances of the objects with actual values in them similar to how you did them, you could just put them in an array literal, unless you were supposed to do it another way.
var instances = [myCruise,myCruise2,myCruise3];

Compare two string objects for matched string

I was just wondering how I could search and compare two string object and check if either contains a matching string.
I have an associative array containing terms and explanations.
I also have this array broken into two objects "keys"(keys showing the key of the associative array) and "values"(values showing the value of each key in array).
I have another associative array containing a dish and its explanation.
I have split the dish's description into separate words put them into an object.
What I would like to do now is check for every word in descsplit search the TermList and return explanation of term found if found.
eg. free-range is contained in dish explanation, check if there is a match for free-range in TermList and return the value(explanation) of free-range.
Any help would be greatly appreciated, Thanks.
var TermList= {
'Al dente' : 'Al dente : Pasta cooked until just firm. From the Italian "to the tooth." ',
'Bake' : 'Bake: To cook food in an oven, surrounded with dry heat; called roasting when applied to meat or poultry.',
'Barbecue' : 'Barbecue: To cook foods on a rack or a spit over coals.',
'Baste' : 'Baste: To moisten food for added flavor and to prevent drying out while cooking.',
'Batter' : 'Batter: An uncooked pourable mixture usually made up of flour, a liquid, and other ingredients.',
'Beat' : 'Beat: To stir rapidly to make a mixture smooth, using a whisk, spoon, or mixer.',
'Blanch' : 'Blanch: To cook briefly in boiling water to seal in flavor and color; usually used for vegetables or fruit, to prepare for freezing, and to ease skin removal.',
'Blend' : 'Blend: To thoroughly combine 2 or more ingredients, either by hand with a whisk or spoon, or with a mixer.',
'Boil': 'Boil: To cook in bubbling water that has reached 100 degrees Celcius.',
'Bone' : 'Bone: To remove bones from poultry, meat, or fish.',
'Bouquet garni' : 'Bouquet garni: A tied bundle of herbs, usually parsley, thyme, and bay leaves, that is added to flavor soups, stews, and sauces but removed before serving.',
'Braise' : 'Braise: To cook first by browning, then gently simmering in a small amount of liquid over low heat in a covered pan until tender.',
'Bread': 'Bread: To coat with crumbs or cornmeal before cooking.',
'Free-range': 'Free-range: (Of livestock, especially poultry) kept in natural conditions, with freedom of movement/ (Of eggs) produced by free-range poultry.'
};
var values = []; // Creating an object for the values of the terms in TermList
var keys = []; // Creating an object for the keys of the terms in TermList
//function to assign the keys of terms to object keys.
function showkey() {
for (var key in TermList) {
if (TermList.hasOwnProperty(key)) {
keys.push(key);
}
}
//function that shows the value of each key in TermList.
function showValue(){
for( var value in TermList){
values.push(TermList[value]);
}
showkey();
showValue();
var DishList={
"Chicken and Stuffing Sandwich": "Chicken and Stuffing Sandwich: Succulent Sandwich made from free-range chicken and fresh breadcrumbs mixed with mayonnaise",
"Eggs Benedict": "Poached eggs served with spinach and hollandaise sauce"
};
var descsplit = [];
function SplitDesc() {
for (var value in DishList) {
descsplit.push(DishList[value].split(/[\s.,?!:]+/)); // Splits the values of the key up in Dishlist, and puts them into array.Also makes them avoid punctuations while splitting.
}
}
SplitDesc();
//For every word in descsplit search the TermList and return explanation of term found if found
Not tested fully, but this may work
var TermList= {
'Al dente' : 'Al dente : Pasta cooked until just firm. From the Italian "to the tooth." ',
'Bake' : 'Bake: To cook food in an oven, surrounded with dry heat; called roasting when applied to meat or poultry.',
'Barbecue' : 'Barbecue: To cook foods on a rack or a spit over coals.',
'Baste' : 'Baste: To moisten food for added flavor and to prevent drying out while cooking.',
'Batter' : 'Batter: An uncooked pourable mixture usually made up of flour, a liquid, and other ingredients.',
'Beat' : 'Beat: To stir rapidly to make a mixture smooth, using a whisk, spoon, or mixer.',
'Blanch' : 'Blanch: To cook briefly in boiling water to seal in flavor and color; usually used for vegetables or fruit, to prepare for freezing, and to ease skin removal.',
'Blend' : 'Blend: To thoroughly combine 2 or more ingredients, either by hand with a whisk or spoon, or with a mixer.',
'Boil': 'Boil: To cook in bubbling water that has reached 100 degrees Celcius.',
'Bone' : 'Bone: To remove bones from poultry, meat, or fish.',
'Bouquet garni' : 'Bouquet garni: A tied bundle of herbs, usually parsley, thyme, and bay leaves, that is added to flavor soups, stews, and sauces but removed before serving.',
'Braise' : 'Braise: To cook first by browning, then gently simmering in a small amount of liquid over low heat in a covered pan until tender.',
'Bread': 'Bread: To coat with crumbs or cornmeal before cooking.',
'Free-range': 'Free-range: (Of livestock, especially poultry) kept in natural conditions, with freedom of movement/ (Of eggs) produced by free-range poultry.'
};
var DishList={
"Chicken and Stuffing Sandwich": "Chicken and Stuffing Sandwich: Succulent Sandwich made from free-range chicken and fresh breadcrumbs mixed with mayonnaise",
"Eggs Benedict": "Poached eggs served with spinach and hollandaise sauce"
};
var keys = Object.keys(TermList);
for(var key in DishList){
var val = DishList[key];
for(var iIndex=0;iIndex<keys.length ;iIndex++){
var term = keys[iIndex];
var regx = new RegExp('\\b'+term+'\\b',"gi");
var found = null;
while((found = regx.exec(val))!=null){
console.log('Found term "'+ term+ '" at index '+found.index);
}
}
}

How to extract number from string using javascript?

I am to trying to extract numbers from string for example
East Texas Baptist University (582) (COL)
North Central Texas Academy (202471) (COL)
Bloomfield College (1662) (COL)
I have used parseInt but it gives me NAN. Can any one please suggest a better way. Thanks
You can use regex for that like:
"Bloomfield College (1662) (COL)".match(/(\d+)/)[0] //1662
Try this:
function getNumber(str) {
return parseInt(str.match(/\d+/)[0], 10);
}
You can use the function like this:
var num = getNumber('East Texas Baptist University (582) (COL)');

How to combine asynchronous calls with synchronous in javascript

I'm kind of beginning to learn javascript and have a question about combining synchronous and asynchronous calls to functions. This will be just a theoric problem, but I hope it transmits the idea.
Let's suppose we have javascript program that decides how many bananas and oranges I need to buy.
console.log('buy %d bananas and %d oranges', bananas, oranges)
Now, I can decide how many bananas I can buy, but I need to ask my wife how many oranges she wants, so I text her. (I can write an async function to represent this).
This would be my immediate approach:
var bananas = 10;
var oranges = 0;
textWife('askAboutOranges',function(number){ oranges = number; }
console.log('buy %d bananas and %d oranges', bananas, oranges)
But to me this doesn't make sense, because I have to wait for my wife to reply, so I probably won't have the number of oranges in time.
So I can change my program to:
var bananas = 10;
var oranges = 0;
textWife('askAboutOranges',function(number){
oranges = number;
console.log('buy %d bananas and %d oranges', bananas, oranges);
}
But I don't like this because now I have the logic of deciding what to buy including the bananas, inside the response from my wife. What if I decide I don't want oranges, do I have to do something like this:
var bananas = 10;
var oranges = 0;
if (wantOranges)
{
textWife('askAboutOranges',function(number){
oranges = number;
console.log('buy %d bananas and %d oranges', bananas, oranges);
}
}
else
console.log('buy %d bananas and %d oranges', bananas, oranges);
So my question is, can anyone explain me what's the best/right way to do something like this?
jQuery Deferred is a great tool to have in your belt. I might do something like this to separate concerns:
function decideHowManyBananas() {
return 10;
}
function decideHowManyOranges() {
var deferred = $.Deferred();
if (wantOranges) {
textWife('askAboutOranges', function(number) {
deferred.resolve(number);
});
} else {
deferred.resolve(0);
}
return deferred.promise();
}
$.when(decideHowManyBananas(), decideHowManyOranges()).done(function(bananas, oranges) {
console.log('buy %d bananas and %d oranges', bananas, oranges);
});
There's no right/best way - it always depends. Modern Javascript libraries use concepts like Deferreds and Promises to synchronize between multiple async calls, sync calls and immediate data. Using jquery, your code might be written as:
$.when({bananas:10, oranges:1}, textWife('askAboutOranges')).done(function(myList, herList) {
buyBananas(myList.bananas);
buyOranges(myList.oranges + herList.oranges);
});
See http://api.jquery.com/category/deferred-object/ for more information.
And this is how to create Deferred objects in your code, in an elegant way:
function decideHowManyOranges() {
if (!wantOranges)
return 0;
return $.Deferred(function(d) {
textWife('askAboutOranges', function(number) {
d.resolve(number);
})
})
}
numOfBananas = 10
$.when(numOfBananas, decideHowManyOranges()).done(function(bananas, oranges) {
console.log('buy %d bananas and %d oranges', bananas, oranges);
});
With Promises
// setup
var bananas = 4
var wantOranges = true
function textWife() { return new Promise((resolve, reject) => setTimeout(() => resolve(8), 1000)) }
// execution
Promise.all([
bananas,
wantOranges ? textWife() : 0 // ternary is necessary here because boolean logs as `NaN`
]).then(([bananas, oranges]) => console.log('buy %d bananas and %d oranges', bananas, oranges))
Note: I am using ..
Promises
Destructuring assignment where var [bananas, oranges] = [4, 8] is same as var bananas = 4, oranges = 8.
Arrow functions () => {}
Prepare a function and use it in both cases to remove code duplication:
var bananas = 10;
var oranges = 0;
function buyStuff() {
console.log('buy %d bananas and %d oranges', bananas, oranges);
}
if (wantOranges)
textWife('askAboutOranges',function(number){
oranges = number;
buyStuff();
})
else
buyStuff();
In your first example, you state that the answer to the question "how many bananas and oranges should I buy?" is dependent on both information you possess, i.e. the number of needed bananas, as well as information you do not possess, the number of needed oranges, so you cannot answer it without first acquiring the missing information.
You then refactor your code to defer answering your question till you possess the missing information which is the typical approach to solving this kind of dependency.
You then state that this doesn't satisfy you because you may not wish to purchase any oranges at all. This is a new requirement and so invalidates your original question, changing it to "how many bananas should I buy?"
By removing the requirement for the missing information, you change the question and so need to special case your problem into two questions.
The final code example you provide does this by first deciding if you need to purchase both bananas and oranges or just oranges, which is indeed the most straightforward way of solving your problem.

Categories