Jquery/Javascript - Can't increment number (tweet-id) - javascript

I don't get it.
I can't increment the Tweet-ID ...
Here is a demo: http://jsbin.com/idupoq/1/edit
glb = {};
glb.lastTweetId = 0;
getTweets();
function getTweets()
{
console.info('# LAST ID');
console.log(glb.lastTweetId);
console.info('# TEST 1');
glb.lastTweetId++;
console.log(glb.lastTweetId);
console.info('# TEST 2');
glb.lastTweetId = glb.lastTweetId+1;
console.log(glb.lastTweetId);
console.info('# TEST 3, OK IS INT BUT PARSE AGAIN ');
glb.lastTweetId = parseInt(glb.lastTweetId);
glb.lastTweetId++;
console.log(glb.lastTweetId);
$.getJSON('http://search.twitter.com/search.json?q=%23wwm&since_id='+glb.lastTweetId+'&include_entities=true&result_type=mixed&lang=de&callback=?', function(data, textStatus)
{
if(data.results.length > 0)
{
glb.lastTweetId = data.results[0]['id'];
}
glb.tm= setTimeout('getTweets();',5000);
});
}
Thanks in advance!

This happens because the received ID is out of range of Number format, e.g.
271567725082578940 + 1 = 271567725082578940
You should use special libraries to work with large numbers. Some examples:
https://github.com/jtobey/javascript-bignum
http://jsfromhell.com/classes/bignumber

As others have said already, it is because of Number cannot express 271567725082578941. If all you ever want to do to this number is to increase it by one, then the following function should be all you need:
function stringInc(v){
var digits = v.toString().split('');
var i = digits.length-1;
while (digits[i]==9 && i>0){
digits[i] = 0;
i--;
}
digits[i] = 1+parseInt(digits[i]);
return digits.join('');
}
If you expect to want to do something more with the number, then you might be better off using a BigNumber library as suggested by VisioN.
Either way, you should note that you cannot read the tweet id from data.results[0]['id'], because that is interpreted as a Number and rounded to 271567725082578940. You need to use data.results[0]['id_str'].
See updated jsbin here: http://jsbin.com/idupoq/19/. Notice the console is logging the result from the server:
...
"geo":null,
"id": 271580395022217200,
"id_str":"271580395022217216",
"iso_language_code":"de"
...
So the value 271567725082578940 that you have been observing is incorrect as well.

Dirty but short
http://jsbin.com/idupoq/18/edit
glb.lastTweetId = ''+data.results[0]['id']+'';
var lastTwoDig = parseInt(glb.lastTweetId.substr(glb.lastTweetId.length-2));
var startDigit = glb.lastTweetId.substring(0, glb.lastTweetId.length-2);
lastTwoDig++;
if(lastTwoDig==01){ lastTwoDig = '01'; }
console.log(glb.lastTweetId);
console.log(' '+startDigit+''+lastTwoDig+' ');

Related

how to get varaiable if only have more than 3 letters javascript

var result="stackoverflow";
var string="22342st";
if(more than 3 letters)
{
var new=data;
}
1)how I can get variable if only have more than
using match() (function ) in javascript
2)what if I do getting variable in for time delay
some (because of TCP connection)
Does anyone have an idea?
you can use .length property to check string length is greater than 3 or not.
var result = "stackoverflow";
if(result.length > 3)
{
//Your business logic goes here
}
if you want to check only character counts in string is greater than three then you can try below code
var input = "45749ce";
var result = input.match(/[a-zA-Z]/gi);
if(result.length > 3)
{
//Your business logic goes here
console.log(`${result} length is greater than 3`);
}
That should work
var myRegEx = /[a-zA-Z(.+)]{3}/g;
var myString="22342st";
if(myString.match(myRegEx)!==null)
{
}
Also
myString.match(myRegEx)
will return an array of matched values, so you can work with them if needed.
To find the more than three letter in variable using match you have to need regex
([a-zA-Z0-9)]){3,}
code how looks like
var result="stackoverflow";
var string="22342st";
var res = string.match(/([a-zA-Z0-9)]){3,}/g);
if(res!=null){
//here what you want
}

Reverse Number in JavaScript

I'm trying to reverse random int in JavaScript. I'm using this code:
'use strict';
function reverse_a_number(n)
{
n = n + '';
return n.split('').reverse().join('');
}
print(reverse_a_number(+gets())); //**+gets()** is like scanner.nextInt in Java and **print();** work's like console.log(); in JS.
This work well if number are not a big integer.
For the first test in my judge, code works correctly:
Input Output
256 652
123.45 54.321
But for BI i get Wrong Answer:
Maybe the best way is to cast array to string... Any suggestions?
The reason is that you cast your get() input to number. Don't do this, use a string as, I think, you receive it. Example:
'use strict';
function gets() {
return '52387456983765.98364593786'
}
function reverse_a_number(n)
{
n = n + '';
return n.split('').reverse().join('');
}
console.log(reverse_a_number(+gets())); // "489.56738965478325"
function reverse_a_number_new(n)
{
return n.split('').reverse().join('');
}
console.log(reverse_a_number_new(gets())); // "68739546389.56738965478325"
To read more about floats in JS: https://javascript.info/number#imprecise-calculations
function reverseNum(n){
var reverse = 0
while(n!=0) {
var rem = n%10
reverse = reverse*10 +rem
n = parseInt(n/10)
}
return reverse
}
reverseNum(523)

Regex to add a space after the fourth chars Javascript

I have a string which is a car number plate. But for display purposes I what to add a space after the fourth char in this string. The data comes from a data service so I have to do this on the front-end
eg. AF13BXP to this AF13 BXP
The code below doesn't seem to work:
var $regtext = $('#regNumber');
if ($regtext.length > 0)
{
var regtext = $regtext.text(),
newRegtext = regtext.replace(/[\n\s]/g, '');
console.log(newRegtext);
}
Simple and clear way to do this, without regex:
var $regtext = $('#regNumber');
if ($regtext.length > 0)
{
var regtext = $regtext.text(),
newRegtext = regtext.substr(0, 4) + " " + regtext.substr(4);
console.log(newRegtext);
}
It's also pretty fast too: runs 10,000 times in 351ms, faster than splitting and joining etc. Good if you'll be processing loads of data from the webservice.
You can use following jquery : Demo
$('.test').keyup(function() {
var foo = $(this).val().split(" ").join("");
if (foo.length > 0) {
foo = foo.match(new RegExp('.{1,4}', 'g')).join(" ");
}
$(this).val(foo);
});
If you want to use regex the following should do it.
newRegtext = regtext.replace(/^(.{4})/,'$1 ')
Try this code
$(document).ready(function(e) {
var $regtext = $('#regNumber');
var $regtext = $regtext.text();
if ($regtext.length > 0)
{
regCheck = /^([A-Z1-9a-z]{1,4})([A-Z1-9a-z]*)$/;
regtext = regCheck.test($regtext);
newRegtext = $regtext.replace(regCheck,"$1 $2");
alert(newRegtext);
}
});

Passing and returning an object to / from a function in Javascript.

I've done some digging on the above topic but am now more confused than when I started.
I have a unit converter that I'm working on.
It's working fine as a base model but I'm now trying to make it more modular.
There are many units and many conversions.
My plan is to have a function that determines what type of conversion is required, temperature, area etc etc, that can then call the appropriate function to carry out the math.
I'm very new to JS which isn't helping matters as it could be a simple mistake that I'm making but it's just as likely that I'm getting huge errors.
I think the problem is passing the object to the next function and then using it.
I've played with the code a great deal and tried many different suggestions online but still no success.
here is my code:
<script type="text/javascript">
function Convert(from, to, units, res){
this.from = from;
this.to = to;
this.units = units;
this.res = res;
}
Convert.convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(this.units.val());
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Convert.prototype.convertTemp = function(){
var result = "invalid input";
var input = parseInt(this.units.val());
var f = this.from.val();
var t = this.to.val()
if(!isNaN(input)) {
if(f == "degC"){
if(t == "degF"){
result = input * 1.8 + 32;
}
if(t == "kelvin"){
result = input + 273.15;
}
}
}
console.log('Parsed input is', input, "and result is", result);
this.res.val(result);
return result;
}
//var calcTempTest = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
//var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
$("#btnConvert").click.convertUnits();
</script>
The first obvious problem is this line:
$("#btnConvert").click.convertUnits();
This tries to call a convertUnits() method defined on the click method of the jQuery object returned by $("#btnConvert"). There is no such method, so you get'll get an error about how click has no method 'convertUnits'.
What you want to be doing there is binding the convertUnits() function as a click handler, which you do by passing it to the .click() method as an argument:
$("#btnConvert").click(Convert.convertUnits)
It doesn't make sense to have declared convertUnits() as a property of Convert(), though, so (although it will work as is) I'd change it to just be:
function convertUnits() {
// your code here
}
$("#btnConvert").click(convertUnits);
The only other thing stopping the code working is that on this line:
var input = parseInt(this.units.val());
...you use this assuming it will be a Convert object with a units property but you haven't yet created a Convert object - you do that inside the if(measurementType == "temp") block with this line:
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
So move that line to the beginning of the function and then use test instead of this:
function convertUnits(){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
var input = parseInt(test.units.val());
if(measurementType == "temp"){
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Working demo: http://jsfiddle.net/jT2ke/
Some unrelated advice: parseInt() doesn't really make sense for a number to feed into your converter, because the user might want to enter decimal values. You can use parseFloat() instead, or the unary plus operator:
var input = +test.units.val();
But if you want parseInt() it is generally recommended to pass it a second argument to specify the radix:
var input = parseInt(test.units.val(), 10);
...because otherwise if the input text has a leading zero some browsers will assume the value is octal rather than base ten. (parseFloat() and the unary plus don't have that issue.)
I think you should not implement the method convertUnits inside Convert object. And the new code will look like the following:
convertUnits = function(){
var measurementType = $(".from option:selected").attr("class");
var result = "invalid input";
if(measurementType == "temp"){
var test = new Convert($("#from"), $("#to"), $("#units"), $("#result"));
test.convertTemp();
console.log('Did we get this far?!?! ::', measurementType);
}
console.log('or not???? ::', measurementType);
}
Now you can initiate the convertUnits on the button click:
$("#btnConvert").click(function(){new convertUnits()});

How can I "count characters" in a regex?

I'm not sure if count is the right word to use because it doesn't really matter to me how many there are, but let me explain. My data will be formatted like this: (hi,(1,2),hey),(yo,(3,(rawr),4),howdy) and I have no control over how many dimensions there are. And I want to grab the lowest groups ["hi", Array[], "hey"] and ["yo", Array[], "howdy"] So if there was a way to "count" I could count the open parenthesis, and then count the closed ones and when it hits 0, that's when the regex ends. For example:
(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)
1---2---1----0-1---2--3----2--1------0
Now with that being said, I don't believe counting is possible but what I want is a subsitute solution. This is what I have so far /\([^\(]*?\)/ but that only returns the highest level group from each of the low-level groups aka (1,2) and (rawr).
You can use a stack to track the (and).
Array.reduce(
'(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)',
function(x,y){
if(y=='(')
return [x[0]+1, x[1]+(x[0]+1)]
else if(y==')')
return [x[0]-1, x[1]+(x[0]-1)]
else
return [x[0], x[1]+'-']
},
[0,'']
)[1]
Try it in firebug console.
This works for the original use-case and #Barmar's use-case - and it counts the parenthesis, if you really wanted that...
Also, I added arbitrary spaces all over the data strings - just in case (since you have no control over the incoming data)
var results = [];
var dataString = "(hi, (1,2) , hey), ( yo,( 3, ( rawr ), 4) , howdy )";
//var dataString = "(hi, (1 , 2 ), (3, 4), hey), (yo ,(3,(rawr ), 4), howdy)";
var dataSplit = dataString.split(",");
var trimRegex = /^\s+|\s+$/g;
var openParensRegex = /\(/;
var closeParensRegex = /\)/;
var parensRegex = /\(|\)/;
var parensCount = 0;
for (var x = 0, lenx = dataSplit.length; x < lenx; x++){
var cleanString = dataSplit[x].replace(trimRegex, "");
if (openParensRegex.test(cleanString)){ parensCount++; };
if (parensCount < 2){
results.push(cleanString.replace(parensRegex, "").replace(trimRegex, ""));
};
if (closeParensRegex.test(cleanString)){ parensCount--; };
};
console.log(results);
Hope that helps!
The following script might help, it will identify the parenthesis levels:
var string="(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)",i=0;
while (string.indexOf("(")>=0) {
i++;
string=string.replace(/\(([^()]+)\)/g,"|l"+i+"|$1|l"+i+"|");
}
Result:
|l2|hi,|l1|1,2|l1|,hey|l2|,|l3|yo,|l2|3,|l1|rawr|l1|,4|l2|,howdy|l3|
Fiddle: http://jsfiddle.net/GfUZh/
If you want to get the highest levels you can probably do it with regex by finding the intersection points, in this case ),(.
var str = '(hi,(1,2),hey),(yo,(3,(rawr),4),howdy)';
var re = /(\(.+\)),(\(.+\))/;
var results = re.exec(str);
results.shift(); // remove first item which is useless
console.log(results); //=> ["(hi,(1,2),hey)", "(yo,(3,(rawr),4),howdy)"]
Demo: http://jsfiddle.net/elclanrs/fFmfE/

Categories