if number is between two numbers by plus/minus 10 addclass - javascript

http://jsfiddle.net/kM8xE/2/
If I have the divs
​
<div class="value">15</div>
<div class="value2">20</div>​
and jQuery
var actual = $(".value").html();
var comparison = $(".value2").html();
how can i add class .isbetween to .value2 if it's html value is between +/-10 of the html for .value ie. for this eg. a value between 5 and 25.
I am not too good but i have tried and it doesn't work.
if(parseInt(actual)-10 <= parseInt(comparison) <= parseInt(actual)+10){
$(".value2").addClass("isbetween");
}

if (Math.abs(actual - comparison) <= 10) {
//they're within 10
}

The reason this doesn't work is that you can't chain comparisons like this:
5 < x < 10
In Javascript (and other languages with c-like syntax), you have to make two separate comparisons, and use the boolean and operator (&&) to chain the comparisons together:
var actualValue = parseInt(actual);
var comparisonValue = parseInt(comparison);
if(actualValue - 10 <= comparisonValue && comparisonValue <= actualValue + 10) {
$(".value2").addClass("isbetween");
}
Also, don't repeat yourself. Do the conversion once, and store it in a local variable. This makes the code much more readable.
This can be made even more simple by using a concept called absolute value. Then you can just do your difference, and see if its absolute value is less than or equal to ten.
var delta = Math.abs(parseInt(actual) - parseInt(comparison));
if(delta <= 10) {
$(".value2").addClass("isbetween");
}

You have to get the two values, convert them to numbers, compare the absolute value of their difference and then add the class if it meets your condition:
var v1 = +$(".value").text();
var v2 = +$(".value2").text();
if (Math.abs(v1 - v2) <= 10) {
$(".value2").addClass("isbetween");
}

Related

Javascript Help - selfDividingNumbers Algorithm producing all 0's

Greetings Stack Overflow!
First off, this is my first question!
I am trying to solve the selfDividingNumbers algorithm and I ran into this interesting problem. This function is supposed to take a range of numbers to check if they are self dividing.
Self Dividing example:
128 is a self-dividing number because
128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
My attempt with Javascript.
/*
selfDividingNumbers( 1, 22 );
*/
var selfDividingNumbers = function(left, right) {
var output = [];
while(left <= right){
// convert number into an array of strings, size 1
var leftString = left.toString().split();
// initialize digit iterator
var currentDigit = leftString[0];
for(var i = 0; i < leftString.length; i++){
currentDigit = parseInt(leftString[i])
console.log( left % currentDigit );
}
// increment lower bound
left++;
}
return output
};
When comparing the current lower bound to the current digit of the lower bound, left % currentDigit it always produces zero! I figure this is probably a type error but I am unsure of why and would love for someone to point out why!
Would also like to see any other ideas to avoid this problem!
I figured this was a good chance to get a better handle on Javascript considering I am clueless as to why my program is producing this output. Any help would be appreciated! :)
Thanks Stack Overflow!
Calling split() isn't buying you anything. Remove it and you'll get the results you expect. You still have to write the code to populate output though.
The answer by #Joseph may fix your current code, but I think there is a potentially easier way to go about doing this. Consider the following script:
var start = 128;
var num = start;
var sd = true;
while (num > 0) {
var last = num % 10;
if (start % last != 0) {
sd = false;
break;
}
num = Math.floor(num / 10);
}
if (sd) {
print("Is self dividing");
}
else {
print("Is NOT self dividing");
}
Demo
To test each digit in the number for its ability to cleanly divide the original number, you can simply use a loop. In each iteration, check num % 10 to get the current digit, and then divide the number by ten. If we never see a digit which can not divide evenly, then the number is not self dividing, otherwise it is.
So the string split method takes the string and returns an array of string parts. The method expects a parameter, however, the dividing element. If no dividing element is provided, the method will return only one part, the string itself. In your case, what you probably intended was to split the string into individual characters, which would mean the divider would be the empty string:
var leftString = left.toString().split('');
Since you are already familiar with console.log, note that you could also use it to debug your program. If you are confused about the output of left % currentDigit, one thing you could try is logging the variables just before the call,
console.log(typeof left, left, typeof currentDigit, currentDigit)
which might give you ideas about where to look next.

JavaScript: Is there a benefit in using the charCode when comparing characters?

First of all: I'm a bit into JavaScript but not much.
Today I saw these code:
if (stringToSearch[i].charCodeAt(0) === codeToSearch) {
The charCodeAt() method of String is used for to compare the current char with the searched char.
The full code of the function here:
function getOccurences (stringToSearch, charToSearch) {
var ret = 0;
var codeToSearch = 0;
var i;
stringToSearch = stringToSearch.toUpperCase();
codeToSearch = charToSearch.toUpperCase().charCodeAt(0);
for (i = 0; i < stringToSearch.length; i++) {
if (stringToSearch[i].charCodeAt(0) === codeToSearch) {
ret++;
}
}
return ret;
}
I would have compared the char directly. Without using charCodeAt().
Just ...
stringToSearch[i] === charToSeach
As far as I know the computer compares just numbers anyway. Translates the characters to their UTF-codes. Subtracts these numbers against each other and then checks if the result has become zero.
So therefore my question:
Does the usage of charCodeAt() makes any sense?
Are there a benefit to favor the direct charCode-comparison over the character-comparison.
My intuition is to say there's a performance hit when you go through type-conversion and function-calling hoops like that.
That said, you'll likely eke out more performance out of the code by delegating to the native string methods, with something like:
function countCaseInsensitiveOccurrences(haystack, char) {
haystack = haystack.toUpperCase();
char = char.toUpperCase()[0];
var count = 0, pos = -1;
while ((pos = haystack.indexOf(char, pos + 1)) !== -1) {
count++;
}
return count;
}
charCode benefits when we have to increment/decrement the characters.
eg. if we have charCode('a') in variable x, then we can increment it using x++.
But if we had saved 'a' then we cannot perform arithmetic operations.
So charCodeAt(number) is used when you need to increment/decrement the characters.

Replace modulus by function

When I try to do 8067 % 80.67 I get 80.66999999999983, instead of 0 beacuse of known floating point javascript behaviour.
So I went and made a function for this, to avoid floating point javascript errors.
function math(a, b) {
var left = Math.abs(a),
times = 1,
abs = a >= 0 ? 1 : -1;
while (Math.abs(a) >= b * times) {
left -= b;
times++;
}
return (a - (b * (times - 1))) * abs;
}
http://jsfiddle.net/s5w3C/
So my question is: is this usefull, ie a good tool to use instead of %? is there cases where this will also give falsy results like the modulus % oprator.
I am looking for a tools to calculate % consistently.
I didn't really inspect the algorithm for correctness, but if you care about efficiency, this is a bad idea. Basically, the larger the input, the slower your code will execute.
I think any fix will only work to a certain level of accuracy and for certain sized numbers. Perhaps something like the following will be sufficient:
function nearlyMod(a, b) {
var precision = ('' + b).split('.').length;
var estimate = (a % b).toFixed(precision);
return estimate == b ? 0 : +estimate;
}
console.log(nearlyMod(8067, 80.66)); // 1
console.log(nearlyMod(8067, 80.67)); // 0
console.log(nearlyMod(8067, 80.68)); // 79.68
It tests if the result is an even divisor within the precision of the original number. If so, it returns 0, otherwise it returns a number to the same precision (which may or may not be what you want).
The result is always a number (the value returned from toFixed is a string, hence +estimate).
A better name might be "roundedMod" or similar.

Comparing negative numbers in JQuery function

I am trying to compare two negative numbers and the comparison is failing. In this specific case, getLeftPercent() is a negative number (-14) yet when comparing, action B is performed. Logically, (-14) is less than (-10) thus action A should be performed.
If I change the right side comparison operand (-10) to a positive number (1 for example) then action A is performed. Is there some quirk of JavaScript that I'm overlooking (which is staring me in the face)? I can post the complete code but there's not really much more.
$(function() {
// the statement in question
if (parseInt(getLeftPercent(), 10) < -10) {
// do action A
// this is just a debug statement
$('#posbanner').html('element position is less than negative 10');
} else {
// do action B
// this is just a debug statement
$('#posbanner').html('element position is greater than or equal to negative 10');
}
});
// element left position on page
function getLeftPercent() {
var leftStr = $('#sidebar').css('left'),
pxPos = leftStr.indexOf('px'),
leftVal = leftStr.substr(0, pxPos),
leftPercent = (leftVal / $(window).width() * 100).toString(),
dotPos = leftPercent.indexOf('.'),
leftPercentStr = dotPos == -1 ? leftPercent : leftPercent.substr(0, dotPos);
return leftPercentStr;
};
I tried running the following code on jsfiddle
if (parseInt( -14, 10) < -10)
{
alert("I am in A");
}
else
{
alert("I am in B");
}
I get I am in A
Not sure, if getLeftPercent() is returning the value you expect.
Your getLeftPercent() function seems way overcomplicated. I'm not sure whether your "left" is relative to the document or parent element, I'll assume document here.
function getLeftPercent() {
'use strict';
return ( ($('#sidebar').offset()).left * 100 / $(window).width() );
}
Most likely your substrings return some characters before the number.
alert(parseInt('-14abc', 10)); // -14
alert(parseInt('abc-14', 10)); // NaN

check whether the number is nearly equal javascript

I want to know whether it is possible?
Let Suppose:
var a = 2592;
var b = 2584;
if(a nearly equal to b) {
// do something
}
Like so.
var diff = Math.abs( a - b );
if( diff > 50 ) {
console.log('diff greater than 50');
}
That would compare if the absolute difference is greater than 50 using Math.abs and simple comparison.
Here's the old school way to do it...
approxeq = function(v1, v2, epsilon) {
if (epsilon == null) {
epsilon = 0.001;
}
return Math.abs(v1 - v2) < epsilon;
};
so,
approxeq(5,5.000001)
is true, while
approxeq(5,5.1)
is false.
You can adjust pass in epsilons explicitly to suit your needs. One part in a thousand usually covers my javascript roundoff issues.
var ratio = 0;
if ( a > b) {
ratio = b / a;
}
else {
ratio = a / b;
}
if (ratio > 0.90) {
//do something
}
One line Es6 way version of The Software Barbarian:
const approxeq = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) <= epsilon;
console.log(approxeq(3.33333, 3.33322)); // true
console.log(approxeq(2.3, 2.33322)); // false
console.log(approxeq(3, 4, 1)); // true
I changed it to include the number in the margin. So with an epsilon margin of 1 approxeq between 1 and 2 is true
Floating point comparison gets complicated in a hurry. It's not as simple as diff less than epsilon in a lot of cases.
Here's an article about the subject, though not javascript specific.
https://floating-point-gui.de/errors/comparison/
TLDR:
When one of the numbers being compared is very close to zero, subtracting the smaller from the larger can lose digits of precision, making the diff appear smaller than it is (or zero).
Very small numbers with different signs work in a weird way.
Dividing by zero will cause problems.
In the article is a function (java) which solves better for these cases:
public static boolean nearlyEqual(float a, float b, float epsilon) {
final float absA = Math.abs(a);
final float absB = Math.abs(b);
final float diff = Math.abs(a - b);
if (a == b) { // shortcut, handles infinities
return true;
} else if (a == 0 || b == 0 || (absA + absB < Float.MIN_NORMAL)) {
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Float.MIN_NORMAL);
} else { // use relative error
return diff / Math.min((absA + absB), Float.MAX_VALUE) < epsilon;
}
}
Before you complain: Yes, that's Java, so you'd have to rewrite it in Javascript. It's just to illustrate the algorithm and it's just copied from the article.
I'm still looking for a thorough solution to this problem, ideally with an NPM package so I don't have to figure this out again every time I need it.
Edit: I've found a package which implements the solution from the article linked above (which has the same link in their readme).
https://www.npmjs.com/package/#intocode-io/nearly-equal
This will be a less error-prone solution than others shown in other answers. There are several npm packages which implement the naive solutions which have error cases near zero as described above. Make sure you look at the source before you use them.

Categories