javascript if value is number to number - javascript

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

Related

NaN output in Javascript from a class function

I need to solve the following problem:
Create class Intern with next fields:
Name(String)
Surname(String)
laziness(number from 20 to 50)
Curiosity (number from 0 to 100)
Skill (number from 0 to 100)
Irresponsibility (float number from 0.0 to 1.0)
For this class create method that calculate “mark” for intern, that is calculated by formula(in the code)
It looks simple, but when I run it, the output is NaN. Could somebody help please?
class Intern {
constructor(name, surname, laziness, curiosity, skill, irresponsibility) {
this.name = name
this.surname = surname
if (laziness <= 50 && laziness >= 20) {
this.laziness = laziness
} else {
this.laziness = 0
}
if (curiosity <= 100 && curiosity >= 0) {
this.curiosity = curiosity
}
if (skill <= 100 && skill >= 0) {
this.skill = skill
}
if (irresponsibility <= 0 && irresponsibility >= 1) {
this.irresponsibility = irresponsibility
}
}
getMark() {
let mark = (((this.skill + this.curiosity) * (1.5 - this.irresponsability)) / (this.laziness * 0.25));
return mark
}
}
You've misspelled the irresponsibility variable in the getMark() method, and the if statement in your constructor for it will never be true:
if (irresponsibility <=0 && irresponsibility >=1)
I think you were meaning to say:
if (irresponsibility >=0 && irresponsibility >=1)

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

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.

Greater than X but less than Y 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;
}
};

Else if statement with 3 or more conditions?

I have been trying for a long time and cant seem to figure out what i'm doing wrong. The first too conditions seem to work but the third fails.
function spriteAI1() {
if (c2Sprite.position.x >= 30 && c2Sprite.position.x <= 450) {
c2Sprite.translateX( -10 );
} else if (c2Sprite.position.x <= 30 && c2Sprite.position.x >= -450) {
c2Sprite.translateX( 10 );
} else if (c2Sprite.position.z = 30 && c2Sprite.position.x = 30) {
c2Sprite.remove;
c2Sprite.clone;
}
else{}
}
function spriteAI2() {
if (c2Sprite.position.z >= 30 && c2Sprite.position.z <= 350) {
c2Sprite.translateZ( -10 );
} else if (c2Sprite.position.z <= -30 && c2Sprite.position.z >= -350) {
c2Sprite.translateZ( 10 );
} else if (c2Sprite.position.x = 30 && c2Sprite.position.z = 30) {
c2Sprite.remove;
c2Sprite.clone;
}
else{}
}
I'm getting an error on the line
else if (c2Sprite.position.x = 30 && c2Sprite.position.z = 30)
the error says invalid left hand in assignment. But the other function has basically the same line and doesn't generate a error.
I can see two problems in your code.
First, comparison is done using == (double equal signs), not a single one (that's assigning a value). That's probably the source of your problem.
In second place, your last two conditions match a common group of values (they are intersected), in the case when c2Sprite.position.x equals 30, it will enter the second "if". It will match the condition for the third one, but it will not run it.
Make sure you always define well-separated groups of conditions (unless that's the behavior that you want).
Just to make it clear:
if (x >= 30) {
/* this matches 30 and above */
}
else if (x == 30) {
/* this won't execute on x == 30, because it entered the first "if" */
}
You should have done this:
if (x > 30) {
/* this matches numbers strictly greater than 30, i.e. 31, 32, 33... */
}
else if (x == 30) {
/* this will match x == 30 */
}
else {
/* any other value for x */
}

Categories

Resources