Once value increments digits stops working - javascript

I have a function so say i have a list:
1,2,3,4,5,6,7,8,9
and if i click say number 3 , number 3 gets removed and all the values larger than this value will be taken away by one so it'd end up looking like this:
1,2,3,4,5,6,7,8
The only problem is that once we start going into the tenths the function just does not work for example if i had:
8,9,10,11,12,13
its meant to look like if i took 9 like:
8,9,10,11,12
but it goes like this:
8,10,11,12
completely ignorning once we get to double figures.... heres what i have:
$("button").each(function(){
if (pad2(cl_on)<pad2($(this).val())){
$(this).val($(this).val()-1);
}
});
i did have a fix for this going upto 99 but once i go over to 100 onwards the same problem resurects, this is the function i have to fix it upto 99...
function pad2(number) {
return (number < 10 ? "0" : "") + number }
There must be something wrong with even having to use this function... can someone help me so i dont have this problem again say if i reach 1000 or 10000?

Convert the strings to numbers, e.g. using unary +. You can also simplify your code to:
$("button").val(function(i, val) {
return +cl_on < +val ? val - 1 : val;
});
As I said in my comment, you are comparing strings, and in lexical(?) order, 10 comes before 2 for example.

What Felix said, or use parseInt() to achieve the same;
$("button").each(function(){
if (parseInt(cl_on, 10) < parseInt($(this).val(), 10)){
$(this).val(parseInt($(this).val(), 10) - 1);
}

Related

How to reverse a string recursively

I was in an interview the other day and I was asked to write a method that reverses a string recursively.
I started writing a method that calls itself and got stuck.
Here is what I was asked, reverse a string "Obama" recursively in JavaScript.
Here is how far I got.
function reverseString(strToReverse)
{
reverseString(strToReverse);
};
And got stuck, they said NO for i loops.
Anyone got any ideas?
Look at it this way: the reversed string will start with the last letter of the original, followed by all but the last letter, reversed.
So:
function reverseString(strToReverse)
{
if (strToReverse.length <= 1)
return strToReverse;
// last char +
// 0 .. second-last-char, reversed
return strToReverse[strToReverse.length - 1] +
reverseString( strToReverse.substring(0, strToReverse.length - 1) );
}
See the solution by #MaxZoom below for a more concise version.
Note that the tail-recursive style in my own answer provides no advantage over the plain-recursive version since JS interpreters are not required to perform tail call elimination.
[Original]
Here's a tail recursive version that works by removing a character from the front of the input string and prepending it to the front of the "accumulator" string:
function reverse(s, acc) {
if (s.length <= 0) { return acc; }
return reverse(s.slice(1), s.charAt(0) + (acc||''));
}
reverse('foobar'); // => "raboof"
The simplest one:
function reverse(input) {
if (input == null || input.length < 2) return input;
return reverse(input.substring(1)) + input.charAt(0);
}
console.log(reverse('Barack Obama'));
Single line solution. And if they asked I tell them it's recursive in the native code part and not to ask any more stupid questions.
var result = "Obama".split('').reverse().join('');
Output: amabO
The real problem here is not "how to reverse a string". The real problem is, "do you understand recursion". That is what the interview question is about!
So, in order to solve the problem, you need to show you know what recursion is about, not that you can reverse the string "Obama". If all you needed to do was reverse the string "Obama", you could write return "amabO"; see?
In other words, this specific programming task is not what it's all about! The real solution is not to copy and paste the code from the answers here, but to know about recursion.
In brief,
Recursion involves calling the same function again, yes, but that's not all
In order to prevent stack overflow, you MUST ensure that the function doesn't call itself indefinitely
So there's always a condition under which the function can exit without calling itself (again)
And when it does call itself again, it should do so with parameters that make the above condition more likely.
In the case of string operations, one way to make that all happen is to make sure that it calls itself only with strings that are shorter than the one it was called with. Since strings are not of an infinite length, the function can't call itself an infinite number of times that way. So the condition can be that the string has a length of zero, in which case it's impossible to call itself with a shorter string.
If you can prove that you know all this, and can use it in a real world program, then you're on your way to passing the interview. Not if you copy and paste some source you found on the internet.
Hope this helps!
We can easily reverse a string in the recursion method using the ternary operator
function reverseString(strToReverse) {
return str.length > 1 ? reverse(str.slice(1)) + str.charAt(0) : str;
}
reverseString("America");
Not the smartest way to reverse a string, but it is recursive:
function reverse(input, output) {
output = output || '';
if (input.length > 0) {
output = output.concat(input[input.length -1]);
return reverse(input.substr(0, input.length - 1), output);
}
return output;
}
console.log(reverse('Obama'));
Here's a jsfiddle
Maybe something like this?
var base = 'Obama',
index = base.length,
result = '';
function recursive(){
if (index == 0) return;
index -= 1;
result += base[index];
recursive();
}
recursive();
alert(result);
jsfiddle:
https://jsfiddle.net/hy1d84jL/
EDIT: You can think of recursion as an infinite for..loop. Let's just use it in "controlled" way and define the bounds - 0 for minimum and the length of Obama word as the maximum. Now, let's just make it call itself whatever number of times and do what you need in order to reverse the string, which is - decrement the index variable by one and sum the character from the end. Hope it helps. Nice question.
If the function can only have the single input i would split the string into smaller and smaller pieces, and add them all together in the reverse order
function reverseString(strToReverse){
if (strToReverse.length <= 1) { return strToReverse; }
return reverseString(strToReverse.substr(1, strToReverse.length - 1) + strToReverse[0];
}

JavaScript if Statement .length not working. Why?

I have this if statement i have came up with here:
var TotalMoney=0;
var Orbs=0;
if (TotalMoney.length==2) {
Orbs+=1;
}
What this code is supposed to do is if the the "TotalMoney" value digit length equals 2,
example (the number 10 has 2 digits)
then it will add 1 "Orb" to the "Orbs" value. Currently, it does nothing. There is HTML and CSS linked to this code but i figured the problem is in this code as it works fine for everything else. Please fix it as i have been trying for hours. Thanks!
For my second question that i just found out with this code here:
var totalMoney=0;
var orbs=0;
if (totalMoney.toString().length==2) {
orbs+=1;
}
This works on getting the number value digits as 2 digits long. The problem now is that once it reaches 10, every time that number goes up (10-99) all the way up, it will add 1 orb each time. I only want it to add 1 orb only when it gets to the 2 digit number (10) and stops adding 1 orb after it reaches it. How can i achieve this? Thanks!
TotalMoney is a number, so it doesn't have a length property. You can check the length of the number by first converting to a string: TotalMoney.toString().length.
Number object in js has no length property, so TotalMoney.length return undefined.
If you want count digits you may use this:
if (TotalMoney.toString().length == 2) {
Orbs+=1;
}
But if TotalMoney will be negative, -1 for exmple, Orbs wil be incremented.
I think there are better way to find all 2-digits number:
if (TotalMoney>9 && TotalMoney<100) {
Orbs+=1;
}
TotalMoney is numeric
so to find its length use this code
TotalMoney.toString().length;
Instead of
TotalMoney.length;
so try to modify your code as below:
var TotalMoney=0;
var Orbs=0;
if (TotalMoney.toString().length==2) {
Orbs+=1;
}
Length is property of array & string.It can not be applied on other variables.
If you want to count number of digits you can do
if(TotalMoney>9)
Or you can convert it to string then check it's length
if(TotalMoney.toSting().length>2)
here are some ideas and general comments on your code.
// recommended to start with lower case. upper case such as 'TotalMoney'
// is stylistically reserved for constructors.
var totalMoney=0;
// again - changing form Orbs to orbs;
var orbs=0;
// recommended to use '===' until you are more experienced with JavaScript and
// know about the 'gotchas' that '==' might produce.
// you will be able to check the length of totalMoney only after converting it to a string.
if (totalMoney.toString().length === 2) {
orbs+=1;
}
Finally, totalMoney of 0 will not add one to orbs. But totalMoney of 10, as you mentioned, will.

convert a big number string to int

i have this html
<p class="res_current tooltip" name="2.969.226.853.669.634.301.755.392" id="current_metal">3 Q</p>
im using this code to get the number of name:
var a = document.getElementById('current_metal').name;
i need to use a to compare like
if(a < 10) { do something }
but the problem is that when i see a (using alert) it return something like this
-> 2,96922685366e+24
so i cant do the if :(, there is a way to get the FULL number without the "."? or convert it
Use parseInt:
parseInt(a, 10);
CAUTION: Do not omit the radix argument!

Backwards JavaScript less-than logic....sometimes

My code couldn't be simpler...
if (iWant > thereAre){
msg = "There's only "+thereAre+" left, but you want "+iWant
} else {
gimmie
}
But sometimes it works.. sometimes it does the else{ every time... sometimes the if{ every time... I will switch the > to a < and then it will still function as before....?
Can JS be broken?
I'm ending up with messages that say "There's only 87 left, but you want 2"... sometimes...sometimes it works great.
The iWant var is getting pulled from a form post
The thereAre var is getting pulled from a MySql COUNT
Please help.. I feel like I'm going crazy.
Sometimes a variable may be a number 4 or the string '4'.
If you want number comparison, not string comparison, then you can multiply by 1 or use parseInt/parseFloat to guarantee that you are dealing with numbers.
if (1*iWant > 1*thereAre ){
too much;
} else {
ok;
}
However, if user input somehow becomes involved and iWant is "two" or "2oops" instead of 2 or "2", this code will still function but not in a useful way.
Optionally you might want to detect non-numbers if it is an issue.

Counting words separated by comma

My counter function looks like that
function count() {
var value = ids.val();
return (value == '') ? 0 : value.replace(/\s,?|,$/g, '').split(',').length;
}
Then checking for returned value and posting data via ajax
if(count() === 10){
ajaxPost();
$(ids).val('');
}
I set interval to use this function. Noting that, tried all other function like change(),paste().. the only way that worked with my scanner device is, to set interval.
The problem is, when i type 9 numbers, like 1...9 and then want to type 10, when I press 1 to write 10 right after 9, it directly posts data. doesn't wait for ",". How can I modify it to wait for "," after last (in this case 10th) word?
You can check the key pressed and see if it is a comma, then only run your code after it is known that the last key entered was a comma:
$(ids).on('keyup', function (event) {
if (event.which == 188) {
if (count(this.value) === 10) {
ajaxPost();
ids.value = '';
}
}
});
10 words with a trailing comma give you 10 commas, consequently, 11 elements in the split result array (the last element will be empty if comma is the last character of the input). Check it like if (count() === 11)....
This should work...
var count = function(str){
var matches = str.match(/.*?,/g);
return (matches == null)? 0 : matches.length;
};
Also you can probably use the keyup or keydown methods to catch this event rather than using a setInterval.
If I were you, I would put this code into a keypress handler. That way it would only be invoked when you type new characters. To prevent it from running the check too often, use _.debounce. Finally, as Andrew mentioned, ",,,,,,,,,,".split(',').length == 11. It appears that you are sabotaging yourself with that regular expression that looks for an optional final comma.
Not sure if I've understood your question completely, but...
You want to wait for a last "," to make sure that all numbers were typed by your scanner? Or you need to get that 10 but the interval occurs just before the scanner finished writing it?
If it is the second case, I recommend you to restart the interval at every keyPressed event. Doing that, you'll give some time just after the key was pressed to wait in case any other key is pressed too.
So, you'll have something like this:
var lastInterval = null
$(ids).keyPress(function() {
if(lastInterval != null)
clearTimeout(lastInterval)
lastInterval = setInterval(function() {
// ... your code here
}, 1000)
})
Is this clear? Hope it helps :)
--- EDIT
Ok, it's weird that a barcode scanner doesn't trigger keyPress events, but taking this as a premise, you could check for changes in the string, and when the string didn't change in N cycles, you trigger your code.
In this example, you'll be sure that the string remained equal at least 1000 ms (between 1000ms and 1999ms).
var lastString = ""
setInterval(function() {
if(lastString == $(ids).val()) { // So, if the value remains the same for 2 cycles, the second one your code will be evaluated
// ... your code here
}
lastString = $(ids).val()
}, 1000)

Categories