How to determine which value has a smaller index in an array - javascript

For a calculator I'm making I have an array with operators in which I need to know whether the times sign comes before or after the division sign. for this I had the following code (using JQuery's inArray):
if ($.inArray('*', operators) < $.inArray(':', operators)) {
//Multiplication is before division so perform mulitplication
}
else {
//Division is before multiplication so perform division
}
Now this code runs in a loop, and every time it removes the operator it has found from the array. This means that at some point there could be only multiplications in the array and no divisions. In the case the inArray function will return for example 3 for the multiplication, and -1 for the division. What you get:
if (3 < -1) ---> false
So it thinks it has found a division sign, where there is none.
It also has to work when it's the other way around: no mulitplication, but only division(s).
I can't come up with solutions to fix this, so that brought me here.

Why do you not use a hash which uses the operators (string) as keys and returns a precedence level (integer) as value?
Some operators have the same precedence level, like plus and minus.
Here is the precedence table for C++ operators, which is much more than you need, but should give you an idea.

One quick and dirty fix is to add an additional check for a '-1' return.
var divIndex = $.inArray(":", operators)
var multiIndex == $.inArray('*', operators)
if (divIndex != -1 && multiIndex < divIndex) {
// multiplication is before division
} else if (divIndex == -1 && multiIndex != -1) {
// only multiplication left
} else if (divIndex != -1 && divIndex < multiIndex) {
// division before multiplication
}

have you tried this?
if ($.inArray('*', operators) < $.inArray(':', operators) || $.inArray(':', operators < 0)) {
...

Test whether there's any division first:
if ($.inArray(':', operators) == -1 || $.inArray('*', operators) < $.inArray(':', operators)) {

Related

How do I modify a function to return true if the given decimal is even when it is rounded to an integer and false otherwise?

I'm working on a Javascript exercise. I am trying to modify a function to return true when the given decimal is rounded to an even number and false when it is not.
So far I have
function isRoundedNumberEven(decimal){
}
console.log(isRoundedNumberEven(2.2), '<-- should be true');
console.log(isRoundedNumberEven(2.8), '<-- should be false');
You have described two steps.
Round the number. This is easily achieved with Math.round()
Determine if it's even or odd. The easiest way to determine this is to divide by 2 and check the remainder. If the remainder is zero, then the number is even. Otherwise, it is odd.
The way you do this is using the modulo operator % - in this case, roundedNumber % 2 would give you the remainder when dividing by 2.
You just need to check if this remainder is 0 or 1, and since you want to "return true if the number is even," then the easy way is return roundedNumber % 2 === 0;
I've provided the tools. Over to you now to assemble them in the right way.
There are two key functions you need here: Math.round(decimal) and the modulo function: "%".
The first will round a decimal value. So, Math.round(2.2) == 2, and Math.round(2.8) == 3.
The second will find the remainder after whole-number division of a number. So, 2%2 == 0, and 3%2 == 1.
Hence, the contents of your function should be:
return Math.round(decimal) % 2 === 0;
function isRoundedNumberEven(decimal){
if((Math.round(decimal)%2) == 0) {
return true;
}
return false;
}

Javascript (-1 <= 5 <= 1) === true?

I want to validate that a given number is within a given range:
function validate(min, max, amount) {
return (min <= amount <= max);
}
But this does not seem to work properly. I know I can do it with two comparison and a logical AND, but I would like to it in one comparison. Is there any NATIVE javascript way to realize this?
Use this instead :
return (min <= amount && amount <= max);
There is no shortcut. And there is a good reason the JavaScript engine can't guess your intent : what you typed was valid, it just isn't interpreted as you'd like. You were testing, in fact
((min <= amount) <= max)
and the result of the first comparison, which is a boolean, is converted to 0 or 1 for the second one (more details here about operators precedence, those comparison operators are left-to-right).
If you really want a shortcut, you could do this :
Number.prototype.isin = function(m,M) {
return m<=this && this<=M;
};
console.log(0.5.isin(1,2)); // logs false
console.log(3..isin(2,5)); // logs true
but I personally would use the standard solution with && that everybody can read and which doesn't involve an additional function call.
Aside : I could have called my function in instead of isin but it might break ES3 browsers.
Operators ( == , <= , < , >= , == ) take only 2 arguments.
When there are more arguments it uses mathematical order of computing. So in fact your code behave like:
min <= amount // true
true <= max // this is illogical
It's also optimal, because when executing logical statements and finding something like:
if(false && (some computing))
It will ignore (some computing) because result will be always false
This is very common practive in every language. Test like this will not have NullPointerException error, because first argument is already false.
if(obj != null && obj.getValue() > 10) //C++,Java, etc.
if(obj !== undefined && obj.val() > 10) // javascript
if(obj.length != 0 && obj.val() > 10) //jQuery

Best way to prevent/handle divide by 0 in javascript

What is the best way to prevent divide by 0 in javascript that is accepting user inputs.
If there is no particular way to achieve this what would be the best way to handle such a situation so as to not prevent other scripts from executing?
Any insights are much appreciated.
There is no way to do that with the normal / and /= operators.
The best way to do what you want is with guards:
function notZero(n) {
n = +n; // Coerce to number.
if (!n) { // Matches +0, -0, NaN
throw new Error('Invalid dividend ' + n);
}
return n;
}
and then do division like
numerator / notZero(denominator)
Alternatively you can always guard the output
function dividend(numerator, denominator) {
var quotient = numerator / denominator;
if (quotient !== quotient) { throw new Error(numerator + " / " + denominator); }
return quotient;
}
but that loses the readability and expressiveness of /=.
Off the top of my head you could:
Check the user input to see if the denominator is zero (or evaluates to zero, depending on what your script actually does).
Check if the result of the action isFinite() and if not then handle appropriately.
what would be the best way to handle such a situation so as to not prevent other scripts from executing
Division by zero doesn't seem to prevent other scripts from execution in JavaScript:
var a = 20;
var b = 0;
var result = a/b;
console.log(result); // returns Infinity
If you want something different to happen in case of division by zero, you could use
function divideIfNotZero(numerator, denominator) {
if (denominator === 0 || isNaN(denominator)) {
return null;
}
else {
return numerator / denominator;
}
}
Hope this is useful
(denominator != 0 ? numerator/denominator : Infinity)
or whatever value you want to put at the end.
Greetings.
To prevent (unwanted) execution
Always verify critical user input and/or results
Use logic and/or callbacks you can prevent to execute
On HTML forms etc. you can use i.e. return false; as value to stop submission.
Why not just check if the denominator is zero?
if(x != 0) z = y / x;
You can also check if the result is Infinity:
3 / 0 == Infinity
Results in true;
(Only tested in chrome.)
A bit different than stopping execution, but the ternary operator is a pretty slick way to customize variable assignment.
var one = 1,
zero = 0,
customValue = 1;
var quotient = zero===0 ? customValue : one / zero;
This way, by setting the customVariable to the integer of your choice, you can expect a predictable result when division by zero occurs.
The best way is contextual. But here's the easiest:
function myFunction( input ){
input = 0 ? 0.0001 : input; // same as if( input == 0 ){ input = 0.0001; }
return 1 / input;
}
Basically if the input is zero, turn it into a very small number before using as a denominator. Works great for integers, since after your division you can round them back down.
A couple caveats prevent this from being universal:
It could cause false positives if your input accepts really small numbers
It won't trigger any error-handling code, if you need to do something special if zero is entered
So it's best for general-purpose, non-critical cases. For example, if you need to return the result of a complex calculation and don't care if the answer is accurate to N digits (determined by 0.0001 vs. 0.00000001, etc.); you just don't want it to break on a divide-by-zero.
As another answer suggested, you could also create a reusable global function.
function divisor( n ){ return ( n = 0 ? 0.0001 : n ); }
function myFunction( input ){ return 1 / divisor( input ); }
Possible improvements:
function divisor( n, orError ){
if( typeof n == 'undefined' || isNaN( n ) || !n ){
if( orError ){ throw new Error( 'Divide by zero.' ); }
return 0.000000000000001;
}else{ return 0 + n; }
}
This would take any value (null, number, string, object) and if invalid or zero, return the failsafe zero-like value. It would also coerce the output to a number just in case it was a string and you were doing something odd. All this would ensure that your divisor function always worked. Finally, for cases where you wanted to handle such errors yourself, you could set the second parameter to true and use a try/catch.
Set a cap on what the value for the numerator can be and set the numerator to that value when the denominator equals 0.
This is a faster approach yet is confusing
let divisor;
let dividend;
let result =(dividend/divisor) || 0
if the result for instance if you are calculating percentage is infinite you can give it 0 as value;
const progress = goal == 0 ? 0 : total/goal

Interesting javascript quirks

I have this following if statement:
RG is "100" and max is "85"
if (RG == "" | RG > max) {
//Doesn't execute
}
Since RG isn't "" and RG is larger than max why isn't the code executing? I believed the operator was short circuiting (hence only the one pipe |) but changing it didn't make any difference. My guess is that it is comparing literal strings - so how do I force javascript to treat them as floats?
Just to be clear I need both parts of the OR to be checked and only execute if either of them is true.
I believed the operator was short circuiting (hence only the one pipe |) but changing it didn't make any difference
I take it then it originally looked like this:
if (RG == "" || RG > max) {
//Doesn't execute
}
We can ignore the first part because it's false, so your question is why wasn't RG > max true? And the answer is that "100" comes before "85" in the string collation order. Strings are not numbers, you don't compare them numerically.
If you want them to be floats as you said, you can make them numbers via parseFloat (or parseInt as they look like integers, but you said floats, so...):
if (RG == "" || parseFloat(RG) > parseFloat(max)) {
//Doesn't execute
}
I've done it inline there, but the odds seem high you'll want to do it earlier and assign the result to variables, unless this really is the only place you'll use the values as numbers.
if (RG === "" || parseFloat(RG) > parseFloat(max)) {
// should execute
}
i prefer
if((!RG) || RG*1>max*1)
{
...
}
How do I force javascript to treat them as floats?
Like this:
var RG = "100",
max = "85";
if (RG === "" || Number(RG) > Number(max)) {
// Your code goes here.
// It will be executed if RG is the empty string OR if RG > max.
}
Number(foo) will coerce foo into a number. You could also use +foo but I think this is more readable.
You should use parseFloat instead if the string can contain text as well.
Note that you need a strict equality check (===) when checking for the empty string, since RG == "" will be true if RG is 0, '0', false, etc. as well.
well, parse the strings.
if (RG == "" | parseFloat(RG) > parseFloat(max)) {
//Do Something }

Regex for 1-10 in javascript for validation

What would be the regex for numbers ranging 1-10 and 1-5? Please help this troubled soul.
You could achive that with easy number checks in javascript:
// Convert input to integer just to be sure
mynum = parseInt(mynum, 10);
// Check number-range
if(mynum >= 1 && mynum <=10)
and
if(mynum >= 1 && mynum <=5)
If you really want to use regex:
/^([1-9]|10)$/
and
/^[1-5]$/
UPDATE:
Fixed the first regex to correctly match the string boundings
Added parseInt to the first example to ensure correct number-checks
This is not a good use of Regular Expressions.
Use simple conditions:
if (x > 0 && x < 6) {
// x is 1 - 5
}
if (x > 0 && x < 10) {
// x is 1 - 10
}
For 1-5 you only need to enclose it as character class:
/^[1-5]$/
For 1-10 you'd just need an additional alternative:
/^([1-9]|10)$/
Is there a reason you want to use regular expressions?
/([1-9]|10)/
Use numeric comparison. The following Number extension can check if a number falls between 2 values:
Number.prototype.between =
function(lower,upper, includeBoundaries){
lower = Number(lower);
upper = Number(upper);
noCando = isNaN(lower) ||
isNaN(upper) ||
lower>=upper;
if ( noCando ) {
throw 'wrong arguments or out of range';
}
return includeBoundaries
? this >= lower && this <= upper
: this > lower && this < upper
};
// usage:
(12).between(1,12); /=> false
(12).between(1,12,true); /=> true
(12).between(0,15,true); /=> true
(0).between(-5,1); //=> true
The function converts the parameters to Number because 0 can evaluate to a boolean in javascript, to be able to check if the paramaters are real number values and to be able to check if lower is not greater than/equal to upper. In those cases an error is thrown.
The includeBoundaries parameter also checks if a Number is equal to lower or upper, if it's not supplied, the function returns a real 'between'-check.
For 1-10 it can be
/^([1-9]|10)$/
and for 1-5 simply
/^[1-5]$/
The answer would be
/^([1-9]|10)$/

Categories