I've read a lot about Data Types in javascript, but found nothing about long int.
I need to know how to define Long Int in javascript.
The reason is the input of following methods of Range object accepts Long data type as second parameter :
var storedSelection = document.createRange();
storedSelection.setStart(document.body, );
storedSelection.setEnd(document.body, );
This Image is captured from WebStorm IDE, please pay attention to type mentioned in this image:
If you've read a lot about JavaScript's data types as you say then you should already know that:
JS variables are loosely typed. That is, when you declare a variable you don't give it a type (only assigned values have a type).
Any given variable can be assigned values of different types at different times. That is, having set x = 12 you can later set x = "some string" or x = { some : "object" } and so forth.
JS only has one number type, floating point numbers (IEEE-754 doubles), so generally speaking no distinction is made between integers and decimals.
I don't know where you read that the range methods accept a "long int data type" as a parameter, but for that parameter you can pass in a JS variable that you know holds an integer, or a numeric literal, or even a function call that returns a number:
function getNumber() {
return 15;
}
var myVariable = 20;
var storedSelection = document.createRange();
storedSelection.setStart(document.body, 12);
storedSelection.setEnd(document.body, myVariable);
storedSelection.setEnd(document.body, getNumber() );
Further reading: https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals
P.S. If you have a non-integer value as a result of a calculation, say you're calculating your range by dividing the total length by three or something, you can force the result to be an integer by rounding to the nearest integer with Math.round() or rounding down with Math.floor() or rounding up with Math.ceil(). See also the Math object.
Related
I have some numbers in json which overflow the Number type, so I want it to be bigint, but how?
{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}
TLDR;
You may employ JSON.parse() reviver parameter
Detailed Solution
To control JSON.parse() behavior that way, you can make use of the second parameter of JSON.parse (reviver) - the function that pre-processes key-value pairs (and may potentially pass desired values to BigInt()).
Yet, the values recognized as numbers will still be coerced (the credit for pinpointing this issue goes to #YohanesGultom).
To get around this, you may enquote your big numbers (to turn them into strings) in your source JSON string, so that their values are preserved upon converting to bigint.
As long as you wish to convert to bigint only certain numbers, you would need to pick up appropriate criteria (e.g. to check whether the value exceeds Number.MAX_SAFE_INTEGER with Number.isSafeInteger(), as #PeterSeliger has suggested).
Thus, your problem may be solved with something, like this:
// source JSON string
const input = `{"foo":[[0],[64],[89],[97]],"bar":[[2323866757078990912,144636906343245838,441695983932742154,163402272522524744],[2477006750808014916,78818525534420994],[18577623609266200],[9008333127155712]]}`
// function that implements desired criteria
// to separate *big numbers* from *small* ones
//
// (works for input parameter num of type number/string)
const isBigNumber = num => !Number.isSafeInteger(+num)
// function that enquotes *big numbers* matching
// desired criteria into double quotes inside
// JSON string
//
// (function checking for *big numbers* may be
// passed as a second parameter for flexibility)
const enquoteBigNumber = (jsonString, bigNumChecker) =>
jsonString
.replaceAll(
/([:\s\[,]*)(\d+)([\s,\]]*)/g,
(matchingSubstr, prefix, bigNum, suffix) =>
bigNumChecker(bigNum)
? `${prefix}"${bigNum}"${suffix}`
: matchingSubstr
)
// parser that turns matching *big numbers* in
// source JSON string to bigint
const parseWithBigInt = (jsonString, bigNumChecker) =>
JSON.parse(
enquoteBigNumber(jsonString, bigNumChecker),
(key, value) =>
!isNaN(value) && bigNumChecker(value)
? BigInt(value)
: value
)
// resulting output
const output = parseWithBigInt(input, isBigNumber)
console.log("output.foo[1][0]: \n", output.foo[1][0], `(type: ${typeof output.foo[1][0]})`)
console.log("output.bar[0][0]: \n", output.bar[0][0].toString(), `(type: ${typeof output.bar[0][0]})`)
.as-console-wrapper{min-height: 100% !important;}
Note: you may find RegExp pattern to match strings of digits among JSON values not quite robust, so feel free to come up with yours (as mine was the quickest I managed to pick off the top of my head for demo purposes)
Note: you may still opt in for some library, as it was suggested by #YohanesGultom, yet adding 10k to your client bundle or 37k to your server-side dependencies (possibly, to docker image size) for that sole purpose may not be quite reasonable.
I have a string containing numbers, I need to extract the numbers from the string and store them into variables. For example, if my user input is:
"make a C++ program that adds 2 numbers together"
Then I need to extract the 2 and store it in a variable.
I tried this:
function hasNumbers(t)
{
var regex = /\d/g;
return regex.test(t);
}
Something like this would be good but I'd prefer it not to be a function.
Either something like var amountOfVariables = or if(userInput.includes,isinteger,typeof, etc.
There has to be a combination of methods that allows you to find a integer in a string & then store it in a variable, right?
I was trying to use document.write(amountOfVariables);
to test if it was being stored but no luck. I know I need to convert the String part into an int.
I want a method or a way to store integers in a users input in variables for later use in functions. But at the moment I can't get this to work.
If I'm not mistaken, the question requires "contains number", not "is number". So:
function hasNumber(myString) {
return /\d/.test(myString);
}
I found a way. not sure if i can use this to find more then 1 number in a string though
const [amountOfVariables] = userInput.match(/\d+/g) || [NaN];
parseInt(amountOfVariables)
document.write(amountOfVariables);
This searches the string for a number then stores it in a variable
I am using BigInt(20) datatype for auto Increment id in mysql database.
and when the integer value is so big then how can I handle this as after the number precision of javascript, it won't to allow to insert and read any number Value. So how can I achieve this.
Read about the big-integer libraries but I won't the expected result
Example:-
var x = 999999999999999999999999999999999999999;
How can I print the same number without using its exponential value and any garbage value ?
I tried like that
var BigNumber = require('big-number');
var x = new BigNumber(999999999999999999999999999999999999999, 10);
console.log(x);
Example2:-
If I get the last inserted Id, then how can I handle this value
connection_db.query('INSERT INTO tableName SET ?', tableData,
function (error1, results1, fields1) {
error1){
// Db error
}else{
var lastInserted = new BigNumber(results1.insertId);
console.log(lastInserted);// still wrong value
}
});
You can only pass/show large numbers like that as strings:
var BigNumber = require('big-number');
var x = new BigNumber('999999999999999999999999999999999999999', 10);
console.log(x.toString())
However, in the end, it's up to the MySQL driver how it handles large numbers like this, because it does have to take into account Number.MAX_SAFE_INTEGER.
For instance, the mysql module has various options (supportBigNumbers and bigNumberStrings) that relate to handling BIGINT.
I have a scenario like this------
right = some_function (some_value)
var idR =right.split('~')[0];
var r =right.split('~')[1];
left = another-func (some_value)
var idL = left.split('~')[0];
var l = left.split('~')[1];
point to be noted that r,l contains numeric values.
My purpose is that I want to take the maximum between r and l, and after that I will traverse back to 'right' or 'left' according to maximum value of r or l.
I am using math.max() but this is not working as it only returns the value, not the name of variable.
How can I achieve my goal???
Let me provide some sample inputs and outputs--
"some_function" returns a string in the format "id~value" where "id" can be "1-1", "2-2" and so on and "value" can be any numeric value. I need to look at the greater "value" and fetch its corresponding "id". Note that "another_func" returns values in same pattern
MY CODE IS NOT THESE TWO BLOCKS ONLY, I HAVE EIGHT FUNCTIONS LIKE THESE AND I HAVE TO TAKE THE BIGGEST NUMBER AND ITS CORRESPONDING ID
Your question is not very clear.
Let's try this, so you have 2 arrays with values r and l and 2 arrays with variable names idR and adL.
Now this is what's not clear, do those arrays containing variable names have the same order? the same values? can this condition be trusted?
You clearly want to get some max value from the values arrays that's ok, but you aren't explaining how the other arrays fit on the picture :) After you do, probably me or someone else can help you :)
I'm writing a JavaScript interpreter for extremely resource-constrained embedded devices (http://www.espruino.com), and every time I think I have implemented some bit of JavaScript correctly I realise I am wrong.
My question now is about []. How would you implement one of the most basic bits of JavaScript correctly?
I've looked through the JavaScript spec and maybe I haven't found the right bit, but I can't find a useful answer.
I had previously assumed that you effectively had two 'maps' - one for integers, and one for strings. And the array length was the value of the highest integer plus one. However this seems wrong, according to jsconsole on chrome:
var a = [];
a[5] = 42;
a["5"]; // 42
a.length; // 6
but also:
var a = [];
a["5"] = 42;
a[5]; // 42
a.length; // 6
So... great - everything is converted into a string, and the highest valued string that represents an integer is used (plus one) to get the length? Wrong.
var a = [];
a["05"] = 42;
a.length; // 0
"05" is a valid integer - even in Octal. So why does it not affect the length?
Do you have to convert the string to an integer, and then check that when converted back to a string, it matches?
Does anyone have a reference to the exact algorithm used to store and get items in an array or object? It seems like it should be very simple, but it looks like it actually isn't!
As the specs said, and was noted by others:
"A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1."
That's explain why in your scenario "5" is considered an array index and "05" is not:
console.log("5" === String("5" >>> 0));
// true, "5" is equal to "5", so it's an index
console.log("05" === String("05" >>> 0));
// false, "05" is not equal to "5", so it's not an index
Note: the Zero-fill right shift is the shortest way in JS to have a substitute of ToUint32, shifting a number by zero.
See MDN
It's possible to quote the JavaScript array indexes as well (e.g.,
years["2"] instead of years[2]), although it's not necessary. The 2 in
years[2] eventually gets coerced into a string by the JavaScript
engine, anyway, through an implicit toString conversion. It is for
this reason that "2" and "02" would refer to two different slots on
the years object and the following example logs true:
console.log(years["2"] != years["02"]);
So with a["5"] you are accessing the array while a["05"] sets a property on the array object.
Arrays are just objects. That means they can have additional properties which are not considered elements of the array.
If the square bracket argument is an integer, it uses it to perform an assignment to the array. Otherwise, it treats it as a string and stores it as a property on the array object.
Edit based on delnan's comment and DCoder's comment, this is how JavaScript determines if it is an appropriate index for an array (versus just a property):
http://www.ecma-international.org/ecma-262/5.1/#sec-15.4
Arrays are also objects.
By doing this
a["05"] = 5;
You are doing the same thing as:
a.05 = 5;
However, the above will result in a syntax error, as a property specified after a dot cannot start with a number.
So if you do this:
a = [];
a["05"] = 5;
you still have an empty array, but the property of a named 05 has the value 5.
The number x is an array index if and only if ToString(ToUint32(x)) is equal to x (so in case of "05" that requirement is not met).