I have an array of objects like
const score_card = [
{ "range":"0.6-1.5", "point":"10"},
{ "range":"1.6-2.5", "point":"20"},
{ "range":"2.6-3.5", "point":"30"},
{ "range":"3.6-4.5", "point":"40"},
{ "range":"4.6+", "point":"50"}
]
Now if I receive a number 1.7 then I need to find out that in which range it falls, so in my example it falls in 1.6-2.5 and associated points for it is 20.
Since the score_card array will be the same all the time, I have used switch case as follows:
let number = 1.7
switch(number) {
case (number>=0.6 || number<=1.5):
console.log('points : 10')
break;
case (number>=1.6 || number <=2.5):
console.log('points : 20')
break;
case (number >=2.6 || number <=3.5):
console.log('points : 30')
break;
case (number>=3.6 || number<=4.5):
console.log('points : 40')
break;
case (number>=4.6):
console.log('points : 50')
break;
default:
console.log('none')
}
Now the problem is the number (in our example 1.7) which we have passed in switch case is a part of an array and this switch case is written inside loop to get number one by one.Which makes code longer and possibly slower And I have to do this 4 more time for different cases.
So can anyone help me and suggest me a way to handle this efficiently?
You have to make changes for your last last condition/range
const score_card = [
{ "range": "0.6-1.5", "point": "10" },
{ "range": "1.6-2.5", "point": "20" },
{ "range": "2.6-3.5", "point": "30" },
{ "range": "3.6-4.5", "point": "40" },
{ "range": "4.6+", "point": "50" }
]
const getPoints = score => {
let points = 0;
score_card.some(slab => {
let [low, high] = slab.range.split('-');
if (score >= +low && score <= +high) points = +slab.point;
})
return points;
}
Related
I can't implement the function tipPercentage that takes the argument rating as a string and return the values:
terrible or poor, then returns 3
good or great, then returns 10
excellent, returns 20
none of the above, returns 0
the input format for custom testing must be that the first line contains a integer, n, denoting the value of rating
HELP FOR A BEGGINNER!!!
You can use a switch statement to do this relatively easily, we check the input rating, then return the relevant tip percentage.
If we don't have a tip percentage for the rating, we'll fall back to the default condition, and return 0.
One could also use a map, though a switch statement is probably more flexible.
// Takes rating as a string and return the tip percentage as an integer.
function tipPercentage(rating) {
switch ((rating + "").toLowerCase()) {
case "terrible":
case "poor":
return 3;
case "good":
case "great":
return 10;
case "excellent":
return 20;
default:
return 0;
}
}
let ratings = ["excellent", "good", "great", "poor", "terrible", "meh", null];
for(let rating of ratings) {
console.log(`tipPercentage(${rating}):`, tipPercentage(rating))
}
function tipPercentage(rating) {
switch(rating) {
case "terrible":
case "poor":
return 3; break;
case "good":
case "great":
return 10; break;
case "excellent":
return 20; break;
default:
return 0;
}
}
Instead of a switch statement you could simply use an object:
const tipPercentage = {
'excellent': 20,
'good': 10,
'great': 10,
'terrible': 3,
'poor': 3,
}
const myRatings = [
"excellent",
"good",
"great",
"terrible",
"whatever",
undefined
];
for (let rating of myRatings) {
// Tip percentage, or 0 if it doesn't exist
console.log(rating, tipPercentage[rating] || 0)
}
I recently started to study javascript
I'm currently watching Javascript course in Udemy.
While code challenging, There's something I cant get it about parameter of 'switch'
let john = {
fullName: 'John Smith',
bills: [124, 48, 268, 180, 42],
calcTips: function() {
this.tips = [];
this.finalValues = [];
for (let i = 0; i < this.bills.length; i++) {
let percentage;
let bill = this.bills[i]
switch (bill) { // If I put parameter as 'bill' variation, The result is only defalut.
case bill < 50:
percentage = 0.2;
break;
case bill >= 50 && bill < 200:
percentage = 0.15;
break;
default:
percentage = 0.1;
}
this.tips[i] = bill * percentage;
this.finalValues[i] = bill + bill * percentage;
}
}
}
john.calcTips();
console.log(john);
However
let john = {
fullName: 'John Smith',
bills: [124, 48, 268, 180, 42],
calcTips: function() {
this.tips = [];
this.finalValues = [];
for (let i = 0; i < this.bills.length; i++) {
let percentage;
let bill = this.bills[i]
switch (true) { // If I put 'ture' as a parameter, It work's. Why?
case bill < 50:
percentage = 0.2;
break;
case bill >= 50 && bill < 200:
percentage = 0.15;
break;
default:
percentage = 0.1;
}
this.tips[i] = bill * percentage;
this.finalValues[i] = bill + bill * percentage;
}
}
}
john.calcTips();
console.log(john);
I've searched in google about this problem.
But I can't find specific way to solve this issue.
I'll appreciate your help.
Switch statements compare values strictly. Which means that you can compare for the exact value of the switch variable.
switch (x) {
case 1: console.log(1); break;
case 2: console.log(2); break;
}
You can do a trick however if you want to make the switch statement work on numerical ranges like this:
var x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
The implementation works on the strict comparison of booleans. The switch statement is for true and will match wherever the case is true.
Related question: Switch on ranges of integers in JavaScript
The switch statement tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. So in this case you switching on a constant value.
More detail :
javascript: using a condition in switch case
I have an array of insurance rates that looks like this
const insuranceRate = [
{
"min_value": 1,
"max_value": 25000,
"add": 328
}, {
"min_value": 25001,
"max_value": 25500,
"add": 331
}, {
"min_value": 25501,
"max_value": 26000,
"add": 335
}, {
"min_value": 26001,
"max_value": 26500,
"add": 338
}]
Let's say I purchase a car at $25,900. How to I find the right object and add $335 to my insurance cost ?
Here you go
const insuranceRate = [
{
"min_value": 1,
"max_value": 25000,
"add": 328
}, {
"min_value": 25001,
"max_value": 25500,
"add": 331
}, {
"min_value": 25501,
"max_value": 26000,
"add": 335
}, {
"min_value": 26001,
"max_value": 26500,
"add": 338
}];
var price=25900;
var filter=insuranceRate.filter(i=>price >= i.min_value && price <=
i.max_value);
console.log("Result:",filter);
Thats pretty simple, have an for loop go through every element and check if ur value is inbetween the min and max values the function would look something like that:
function F(value){
for( i=0;i<insuranceRate.length;i++){
if ( value >= insuranceRate[i].min_value && value <= insuranceRate[i].max_value){
return insuranceRate[i];
}
}
return -1;
}
which returns the element within the range, which u then can use to get your add value, also if ur value is not between the range, it'll return -1
If you want the one with the lowest price I'd go with this:
var valid_rates = [];
insuranceRate.forEach((item, index)=>{
if (price >= item.min_value && price <= item.max_value) {
valid_rates.push(item.add) ;
}
}) ;
// Lowest price
Math.min(valid_rates) ;
Loop over the aray and check whether your car cost is in the range, if so - add it to the insurance cost - in this example I initialized it with 0:
var my_car = 25900;
var insuranceCost = 0;
for (var i=0; i<insuranceRate.length; i++) {
if (my_car >= insuranceRate[i].min_value &&
my_car <= insuranceRate[i].max_value) {
insuranceCost += insuranceRate[i].add;
}
}
console.log(insuranceCost); //335
I recently saw a roulette wheel of sorts which contained the following possible numbers. 1, 2, 9, 16, 24, 49j and 49f. Each number has odds of itself over 1. So the odds of rolling a 2 are 2/1 and a 9 is 9/1. I thought it would be a fun (and simple) exercise to populate an array with the right amount of each type of number but it's proved anything but. My first idea was to build a name/value array to hold each numbers odds and then a second one to hold a counter value.
let numbers = {
"1": "1",
"2": "2",
"9": "9",
"16": "16",
"24": "24",
"49f": "49",
"49j": "49"
};
let counter = {
"1": "0",
"2": "0",
"9": "0",
"16": "0",
"24": "0",
"49f": "0",
"49j": "0"
};
let tc = {
"1": "0",
"2": "0",
"9": "0",
"16": "0",
"24": "0",
"49f": "0",
"49j": "0"
};
That last one tc is just to tally how many of each number is in the final array and confirm my mathematical genius. So from here it should be a simple matter of looping 50 times and looping through each number, incrementing its counter by 1 and when the counter value equals the odds value, push that number into the array and reset its counter to 0. So each iteration I should get a 1 and every 3rd iteration I should get a 2 and so on.
var wheel = [];
function load_numbers( ) {
for(let number in numbers) {
var count = parseInt(counter[number], 10);
var odd = parseInt(numbers[number], 10);
var t = parseInt(tc[number], 10);
count++;
if (count == odd) {
wheel.push(number);
count = 0;
t++; tc[number] = t;
}
counter[number] = count;
}
}
function load_wheel( ) {
for (i = 0; i < 50; i++) {
load_numbers();
}
for(let mc in tc) {
document.write(mc + ": " + tc[mc] + " of " + wheel.length + " <br>");
}
}
However that code produces the following
1: 50 of 87
2: 25 of 87
9: 5 of 87
16: 3 of 87
24: 2 of 87
49f: 1 of 87
49j: 1 of 87
These odds are clearly wrong but I can't see what's wrong with the method, I've tried doubling the odds and looping 100 times, still wrong. Setting a breakpoint after 49j == 1 also gives me these odds. In desperation I tried calculating the percentage of each numbers odds and adding them together (ie 1 = 50%, 2 = 33%) and that procedure keeps giving me 108%! So at this point I have to conclude I've been wrong about math my whole life or the Casino is pulling a fast one! Or is there something I'm overlooking?
I'm currently working on an idle game and have encountered a problem.
I'm trying to create a function that will lessen the value of 1 of 6 variables (each represents a type of worker) a number of times. However, if one of these 6 variables is at 0, I need it to pick one of the other 5, and I can't get that to work.
With fiddling around, I have gotten this:
function killWorker(amount){
var job;
for (var i=0;i<amount;i++){
job = Math.floor((Math.random()*6)+1);
switch (job){
case 1:
if(unass_workers>0){
unass_workers -= 1;
}else{
i-=1;
}
case 2:
if(farm_workers>0){
farm_workers -= 1;
}else{
i-=1;
}
break;
case 3:
if(tree_workers>0){
tree_workers -= 1;
}else{
i-=1;
}
break;
case 4:
if(metMine_workers>0){
metMine_workers -= 1;
}else{
i-=1;
}
break;
case 5:
if(golMine_workers>0){
golMine_workers -= 1;
}else{
i-=1;
}
break;
case 6:
if(paper_workers>0){
paper_workers -= 1;
}else{
i-=1;
}
break;
default:
console.log("error: killWorker() didn't work properly");
break;
}
}
}
This worked when I did low amounts, but when I increased the amount higher the whole thing crashed. I'd be quite happy to drastically change the function if it would work better, and I am using jquery too if that could help get an easier or more effective solution.
As i said, what probably happens is that amount is larger than the sum of X_workers, resulting in an infinite loop.
A fix that keeps your logic correct would be to check that enough workers can be killed:
function killWorker(amount){
if (amount < unass_workers + farm_workers + ...) return "Genocide";
var job;
for (var i=0;i<amount;i++){
...
}
A better way to organize your data structures could be:
var workerNames = [ 'unass', 'farm', 'tree', 'metMine', 'golMine', 'paper' ];
var workers = {
unass : 23,
farm : 45,
tree : 6,
metMine : 99,
golMine : 3,
paper: 43
}
function getRandomLiveJobName() {
var jobs = workerNames.filter(function(name) {
return workers[name] > 0;
});
return jobs[Math.floor(Math.random()*jobs.length)];
}
function killWorkers(amount) {
for (;amount--;) {
var job = getRandomLiveJobName();
if (!job) return "Genocide";
workers[job]--;
}
}
killWorkers(150);
console.log(workers); // { farm: 0, golMine: 0, metMine: 64, paper: 5, tree: 0, unass: 0 }
Of course it could be optimized by not creating a new array each time you need a random live job by updating a single array inside killWorkers, but i think it's easier to read now.