Greater than X but less than Y javascript - javascript

I am new here, but i'm simply trying to figure out why this javascript is not working in my math program.
For the last two IF statements, i'm comparing numbers. Greater than X but less than Y...
(function(){
if(fieldname4-fieldname3 < 30) return (1));
if ((fieldname4-fieldname3 > 31) && (fieldname4-fieldname3 < 60)) return
(2);
if ((fieldname4-fieldname3 > 60) && (fieldname4-fieldname3 < 90)) return
(3);
})();
Thanks for any help you can give me.
EDIT: I'm going to post the full script when i'm back to my compuer. Sorry for being so vague. It wasn't intentional. I'm still learning.

You can try to write a better code. For example:
(function(){
if(fieldname4-fieldname3 < 30){
return 1; //returns 1 for every number smaller then 30
}
if(fieldname4-fieldname3 >= 30 && fieldname4-fieldname3 <= 60){
return 2; // returns 2 for every number smaller then 60(includes 60) and greater then 30(includes 30)
}
if(fieldname4-fieldname3 > 60 && fieldname4-fieldname3 < 90){
return 3; // returns 3 for number smaller then 90 and greater then 60
}
})();
I hope that this will help you

Just shooting at it in the dark without seeing the script but how about this??
function test (fieldname4, fieldname3) {
var fieldResult = fieldname4 - fieldname3;
if(fieldResult < 30) {
return 1;
} else if ((fieldResult > 31) && (fieldResult < 60)) {
return 2;
} else if ((fieldResult > 60) && (fieldResult < 90)) {
return 3;
}
};

Related

Grading Students in JS with recursion - Range Error

I was trying to work on this hackerrank problem.
Every student receives a grade in the inclusive range from
0-100 to .
Any less than 38 is a failing grade.
Sam is a professor at the university and likes to round each student's according to these rules:
If the difference between grade the and the next multiple of
5 is less than 3, round up to the next multiple of 5. If the value of grade is less than 38, no rounding occurs as the
result will still be a failing grade.
Given the initial value of for each of Sam's students, write code to
automate the rounding process.
My code is:
function gradingStudents(grades) {
const roundup = y => y + 1;
{
if ( grades < 38 || grades % 5 === 0) return grades;
else if ( grades % 5 < 4 && grades % 5 !== 0) return roundup(grades);
}
{
if (roundup % 5 === 0) return roundup;
else { gradingStudents(roundup + 1) }
}
}
gradingStudents(38) // -> 39
I tried to use Math.ceil(grades) inside the variable roundup but output didnt change. So, when you invoke the function with a number that is not before a multiple of 5 (e.g. 43) it returns the proceeding number. However, if it is the number before a multiple of 5 it gives a range error. "maximum call stack size reached."
As far as I got, the code doesnt proceed to the second part. Even if it did, I am not sure if it would fetch the current value of the function roundup when dealing with if statements in the second block.
What do I dont get in here?
Also, this is actually meant for an array output but since I am a beginner I am pretty much okay with this one for the start as well :D .
Javascript solution:
function gradingStudents(grades) {
return grades.map((grade) => {
if (grade > 37) {
const offset = 5 - (grade % 5);
if (offset < 3) {
grade += offset;
}
}
return grade;
});
}
Try this:
function gradingStudents(grades) { //input: 43
var finalGrade;
if(grade < 38)
return grades;
else{
var gradeDif = grades % 5; //3
if(gradeDif > 3){
return grades;
}
else {
return grades + (5 - gradeDif); //Output: 45
}
}
}
One solution calculates the next multiple of 5 no bigger than the grade and uses that value to test whether or not to round up (next5 - grade < 3).
We write a simple function to round an individual grade and then for a list of grades use .map with that function.
const roundGrade = (grade) => {
const next5 = 5 * Math.ceil (grade / 5)
return (grade < 38) ? grade : (next5 - grade < 3) ? next5 : grade
}
const gradingStudents = (grades) =>
grades .map (roundGrade)
console .log (gradingStudents ([73, 67, 38, 33]))
Note that, like most solutions to this problem, no recursion is needed.
1-Use the Array.prototypt.map according to the question logic.
const gradingStudents = (grades) => grades
.map(n => (n >= 38 && n % 5 >= 3)?(n + ( 5 - ( n % 5 ) )):n )
let result = gradingStudents([0,25,38,56,89,77,78,57,58])
console.log(result)
My solution is this
function gradingStudents(grades) {
grades.map((grade,i)=>{
if(grade >= 38){
let fg = (grade/5).toString().split('.');
if(fg[1]>5){
grades[i]=((parseInt(fg[0],10)+1) * 5);
};
}
});
return grades;
}
console.log(gradingStudents([73,67,38,33]));
my solution:
function gradingStudents(grades) {
return grades.map(function(grade) {
return (grade >= 38 && grade % 5 >= 3) ? grade + 5 - (grade % 5) : grade;
});
}

Recursively setting a value depending on range using JavaScript

I don't know how to word this but this is what I'm trying to do:
if (score >= 0 && score <= 10) overallScore = 0;
else if (score >= 11 && score <= 20) overallScore = 1;
else if (score >= 21 && score <= 30) overallScore = 2;
else if (score >= 31 && score <= 40) overallScore = 3;
else if (score >= 91 && score <= 100) overallScore = 9;
...
Is there any way to recursively do this using a function?
overallScore = Math.max(0, Math.floor((score - 1) / 10));
no need for recursion. But if you need that:
const getOverall = score => score <= 10 ? 0 : getOverall(score - 10) + 1;
Recursion is not really appropriate here, since you can get the required value in constant time. Recursion becomes interesting when you need at least O(logn) time.
But as you ask for it, here is one way to make it recursive:
function range(score, depth = 0) {
return score <= 10 || depth >= 9 ? 0 : range(score-10, depth+1) + 1;
}
console.log(range(0)); // 0
console.log(range(10)); // 0
console.log(range(11)); // 1
console.log(range(60)); // 5
console.log(range(91)); // 9
console.log(range(110)); // 9

How can I convert these 'if' statements to an algorithm

I'm trying to convert these 'if' statements to an algorithm, so that I can have many more stages instead of being limited to 10. How would I go about converting it? I just can't wrap my head around the logic!
function getStage(km) {
if (km > 2 && km < 4){
return 1;
}
else if (km > 4 && km < 6){
return 2;
}
else if (km > 6 && km < 8){
return 3;
}
else if (km > 8 && km < 10){
return 4;
}
else if (km > 10 && km < 12){
return 5;
}
else if (km > 12 && km < 14){
return 6;
}
else if (km > 14 && km < 16){
return 7;
}
else if (km > 16 && km < 18){
return 8;
}
else if (km > 18 && km < 20){
return 9;
}
else if (km > 20 && km < 22){
return 10;
}
}
I have tried this:
function getStage(km) {
var tempStage = 0;
for (var i = 0; i < stages; i++) {
var stage = i + 1;
var tempKm = stage * 2;
var nextKm = stage + 2;
if (km > tempKm && km < nextKm) {
tempStage = stage;
}
}
return tempStage;
}
Perhaps I shouldn't be using a for loop? Is there a better way of doing this?
Maybe you are looking for Math.floor
function getStage(km) {
return Math.floor(km / 2)
}
console.log(getStage(2));
// 1
console.log(getStage(10));
// 5
console.log(getStage(11));
// 5
You can just use math to do this. No loops or conditionals necessary.
Notice that your input intervals increase in "steps" of 2, and your outputs increase in "steps" of 1. This makes me think maybe we should divide km by 2.
Since we always want an integer answer, we can use the Math.floor function.
Some examples:
Math.floor(3/2) = 1
Math.floor(4.1/2) = 2
etc.
Depending on what you want to return for edge cases (what if km = 2 or km = 4, or any multiple of 2?) we might be done here. If you wish to return 1 when k=4, 2 when k=6, etc., you'll need to do a little more work.
*** In general: *** if you are working with numbers and you find yourself writing a lot of cases, you can usually use some combination of simple mathematical operators to calculate the result. For problems like these, try thinking about your input/output pairs, and what the relationship is between them.
You could take the floored value of km divided by two plus one.
10 is the upper limit.
function getStage(km) {
return Math.min((km >> 1) + 1, 10);
}
console.log(getStage(2.1)); // 2
console.log(getStage(3)); // 2
console.log(getStage(4)); // 4
Try something like this. This is general solution which applies not only to 2*n series.
const stages = [2, 4, 6, 8, 10, 13, 15, 16, 20]; //should be ordered. Else sort it first.
const getStage = km => stages.indexOf(stages.find(i => km < i));
console.log(getStage(5)); //2
console.log(getStage(1.5)); //0
console.log(getStage(8.1)); //4
console.log(getStage(15)); //7
console.log(getStage(22)); //-1 out of index

Is there a way I can make this into a function or anything more efficient

if (one >= 16 && one <= 20){
if (two >= 10){
Sum.innerHTML = "$2750";
} else {
Sum.innerHTML = "$2500";
}
} else if (one >= 20 && one <= 25){
if (two >= 10){
Sum.innerHTML = "$2500";
} else {
Sum.innerHTML = "$2250";
}
}
This is just a little of my code, its just a simple money calculator for something I'm doing with a friend, which doesn't really matter. I can't seem to think if there is any way I can make this more efficient by using a function of such because it just seems so much of the same code and is "dry" this is not all the code from it, there is so much of this... Don't know if anyone can help FYI this is in js and Sum is a paragraph id so just think of it as console log.
Thanks, Ethan
EDIT
https://codepen.io/anon/pen/bxgYWL?editors=10100
If you go onto that you can see all the code with all the commenting I could think to add to try and help you understand. Don't worry if it doesn't help and if there is no other way to make it efficient. It doesn't REALLY matter because it's just a private bit of code and shouldn't cause many problems.
You can use a data structure to hold the range boundaries, then loop over it.
var params = [
{ onelow: 16, onehigh: 20,
two: [ { low: -inf, high: 9, value: 2500 },
{ low: 10, high: +inf, value: 2750 }],
},
{ onelow: 21, onehigh: 25,
two: [ { low: -inf, high: 9, value: 2250 },
{ low: 10, high: +inf, value: 2500 }],
},
...
];
let done = false;
for(let i = 0; !done && i < params.length; i++) {
let param = params[i];
if (one >= param.onelow && one <= param.onehigh) {
let done = false;
for (let j = 0; j < param.two.length; j++) {
let param2 = param[j];
if (two >= param2.low && two <= param2.high) {
Sum.innerHTML = "$" + param2.value;
done = true; // stop the outer loop, too
break;
}
}
}
}
At first your this part of code:
if(two >= 10)
{
Sum.innerHTML = "$2750";
}
else
{
Sum.innerHTML = "$2500";
}
we could rewrite to more shorter code:
Sum.innerHTML = two >= 10 ? "$2750" : "$2500";
And then because your this part of code repeats all the time we could write it in function like follows:
function setSum(compareValue, ifValue, elseValue)
{
Sum.innerHTML = two >= compareValue ? ifValue : elseValue
// or even: Sum.innerHTML = two >= 10 ? ifValue : elseValue
}
And after this we can short your code from your example on codepen like in following example:
var numOne = document.getElementById("one"),
numTwo = document.getElementById("two"),
Sum = document.getElementById("sum");
numOne.addEventListener("input", calc);
numTwo.addEventListener("input", calc);
function setSum(compareValue, ifValue, elseValue)
{
Sum.innerHTML = two >= compareValue ? ifValue : elseValue
// or even: Sum.innerHTML = two >= 10 ? ifValue : elseValue
}
function calc()
{
var one = parseFloat(numOne.value) || 0,
two = parseFloat(numTwo.value) || 0;
if(one >= 16 && one <= 20)
setSum(10, "$2750", "$2500");
else if(one >= 20 && one <= 25)
setSum(10, "$2500", "$2250");
else if(one >= 25 && one <= 35)
setSum(10, "$2000", "$1750");
else if(one >= 35 && one <= 45)
setSum(10, "$1500", "$1250");
else if(one >= 45 && one <= 50)
setSum(10, "$1250", "$1000");
}
<h4>Calculator</h4>
<p>
<input id="one"> + <input id="two">
</p>
<p id="sum"></p>
I do not really understand what your calculater does, but you wrote:
This is just a little of my code, its just a simple money calculator for something I'm doing with a friend, which doesn't really matter.
You can optimize your code as following (UPDATED):
var temp = "$2500"
if (one >= 16 && one <= 20){
if (two >= 10){
temp = "$2750";
}
} else if (one >= 20 && one <= 25){
if (!(two >= 10)){
temp = "$2250";
}
}
Sum.innerHTML = temp;
You don't always need to write an else, it can be avoided like in the above code. If you have to change the value, then set one value that is going to be same always, and change the value if the condition is satisfied.
I hope my answer was meaningful. Thanks.

javascript if value is number to number

Is there any way to check if value is in a number range? Like my example:
if (battery.level == 70 to 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
}
What's the syntax for that? Thanks for help.
if (battery.level >= 70 && battery.level <= 100) {
something like this
if ( value >= 70 && value <= 100)
{
}
You could do this :
function inRange(n, from, to) {
return n >= from && n <= to;
}
if (inRange(battery.levelPercent, 70, 100))
YOU CAN CHECK NUMBER LIKE
if ( battery.level >= 70 && battery.level <= 100)
{
}
NOT A STRING LIKE ('70%' to '100%')
70% is actually not a number. However, you could get rid of the invalidating % by naming your variable battery.levelPercent instead and adding the percent sign whenever it needs to be output.
Then, you could check the number like this:
if (typeof battery.levelPercent === "number") {
if (battery.levelPercent >= 70 && battery.levelPercent <= 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
} // else, not in range
} // else, not a number
You better remove % from battery.level to compare it with number.
Live Demo
level = battery.level.replace('%', '');
if (level >= 70 && level <= 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
}
You can also use parseFloat or parseInt
level = parseFloat(battery.level);
if (level >= 70 && level <= 100) {
$('#battery').css('background-image', 'url("battery_full.png")');
}

Categories

Resources