Creating a random number for a local storage keyName [duplicate] - javascript

This question already has answers here:
Generate random string/characters in JavaScript
(93 answers)
Closed 8 months ago.
I am trying to create a random number as the keyName for a local storage for example in this code:
localStorage.setItem('_8bcsk999r778311o', input.value);
I want to create a random number in the place of "_8bcsk999r778311o" using javascript . Is it possible , and if possible , could you please send me the code? Thanks in advance!

const random_id = `_${Math.random().toString(30).substr(2,17) + Math.random().toString(30).substring(2,17)}`
console.log(random_id)
//localStorage.setItem(random_id, 'value goes here');
Very simple and fast solution

Takes a number from 1 to 10 and save into number then with floor convert number to integer
//random integer from 0 to 10000:
let number = Math.floor(Math.random() * 10000);
localStorage.setItem(number, input.value);
In JavaScript, floor() is a function that is used to return the largest integer value that is less than or equal to a number.
see more
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):
see more

var key = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < Math.floor(10+10*Math.random()); i++) {
key += possible.charAt(Math.floor(Math.random() * possible.length));
}
localStorage.setItem(key, input.value);
I hope this will be helpful for you. Thanks.

You could utilise the random nature of the window.crypto object to deliver your numeric / string IDs with a simple function as below. By tweaking the input arguments you can easily generate either numeric or alphanumeric strings of varying sizes.
Uint32Array
crypto.getRandomValues()
const uniqid = (length = 2, base = 16) => {
let t = [];
// invoke the crypto
let crypto = window.crypto || window.msCrypto;
// create a large storage array
let tmp = new Uint32Array(length);
// populate random values into tmp array
crypto.getRandomValues( tmp );
// process these random values
tmp.forEach(i => {
t.push( Math.floor( i * 0x15868 ).toString( base ).substring( 1 ) )
});
return t.join('');
}
// purely numeric using Base10
console.info( 'Numeric - Base 10: %s', uniqid(2, 10) );
console.info( 'Long Numeric - Base 10: %s', uniqid(4, 10) );
// Alphanumeric strings using Base16
console.info( 'Alphanumeric String - Base 16: %s', uniqid(2, 16) );
console.info( 'Long Alphanumeric String - Base 16: %s', uniqid(4, 16) );

Related

in Javascript, exist a function that return only the fractional part of a number, like Math dot something.... ? How can I get it? [duplicate]

I have a floating point number:
var f = 0.1457;
Or:
var f = 4.7005
How do I get just the fraction remainder as integer?
I.e. in the first example I want to get:
var remainder = 1457;
In the second example:
var remainder = 7005;
function frac(f) {
return f % 1;
}
While this is not what most people will want, but TS asked for fract as integer, here it is:
function fract(n){ return Number(String(n).split('.')[1] || 0); }
fract(1.23) // = 23
fract(123) // = 0
fract(0.0008) // = 8
This will do it (up to the 4 digits that you want, change the multipler (10000) to larger or smaller if you want smaller or larger number):
Math.ceil(((f < 1.0) ? f : (f % Math.floor(f))) * 10000)
parseInt(parseFloat(amount).toString().split('.')[1], 10)
You can subtract the floor of the number, giving you just the fractional part, and then multiply by 10000, i.e.:
var remainder = (f-Math.floor(f))*10000;
I would argue that, assuming we want to display these values to the user, treating these numbers as strings would be the best approach. This gets round the issue of fractional values such as 0.002.
I came accross this issue when trying to display prices with the cents in superscript.
let price = 23.43; // 23.43
let strPrice = price.toFixed(2) + ''; // "23.43"
let integer = strPrice.split(".")[0] // "23"
let fractional = strPrice.split(".")[1] // "43"
This also depends on what you want to do with the remainder (as commenters already asked). For instance, if the base number is 1.03, do you want the returned remainder as 3 or 03 -- I mean, do you want it as a number or as a string (for purposes of displaying it to the user). One example would be article price display, where you don't want to conver 03 to 3 (for instance $1.03) where you want to superscript 03.
Next, the problem is with float precision. Consider this:
var price = 1.03;
var frac = (price - Math.floor(price))*100;
// frac = 3.0000000000000027
So you can "solve" this by slicing the string representation without multiplication (and optional zero-padding) in such cases. At the same time, you avoid floating precision issue. Also demonstrated in this jsfiddle.
This post about floating precision might help as well as this one.
var strNumber = f.toString();
var remainder = strNumber.substr(strNumber.indexOf('.') + 1, 4);
remainder = Number(reminder);
Similar method to Martina's answer with a basic modulo operation but solves some of the issues in the comments by returning the same number of decimal places as passed in.
Modifies a method from an answer to a different question on SO which handles the scientific notation for small floats.
Additionally allows the fractional part to be returned as an integer (ie OP's request).
function sfract(n, toInt) {
toInt = false || toInt;
let dec = n.toString().split('e-');
let places = dec.length > 1
? parseInt(dec[1], 10)
: Math.floor(n) !== n ? dec[0].split('.')[1].length : 0;
let fract = parseFloat((n%1).toFixed(places));
return toInt ? fract * Math.pow(10,places) : fract;
};
Tests
function sfract(n, toInt) {
toInt = false || toInt;
let dec = n.toString().split('e-');
let places = dec.length > 1
? parseInt(dec[1], 10)
: Math.floor(n) !== n ? dec[0].split('.')[1].length : 0;
let fract = parseFloat((n%1).toFixed(places));
return toInt ? fract * Math.pow(10,places) : fract;
};
console.log(sfract(0.0000005)); // 5e-7
console.log(sfract(0.0000005, true)); // 5
console.log(sfract(4444)); // 0
console.log(sfract(4444, true)); // 0
console.log(sfract(44444.0000005)); // 5e-7
console.log(sfract(44444.00052121, true)); // 52121
console.log(sfract(34.5697)); // 0.5697
console.log(sfract(730.4583333333321, true)); // 4583333333321
#Udara Seneviratne
const findFraction = (num) => {
return parseInt( // 5.---------------- And finally we parses a "string" type and returns an integer
// 1. We convert our parameter "num" to the "string" type (to work as with an array in the next step)
// result: "1.012312"
num.toString()
// 2. Here we separating the string as an array using the separator: " . "
// result: ["1", "012312"]
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
.split('.')
// 3. With help a method "Array.splice" we cut the first element of our array
// result: ["012312"]
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
.splice(1.1)
// 4. With help a method "Array.shift" we remove the first element from an array and returns that
// result: 012312 (But it's still the "string" type)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
.shift()
)
}
// Try it
console.log("Result is = " + findFraction (1.012312))
// Type of result
console.log("Type of result = " + typeof findFraction (1.012312))
// Some later operation
console.log("Result + some number is = " + findFraction (1.012312) + 555)

How to convert hex to decimal WITH A LOOP in JavaScript

Is it possible to convert a hex number to a decimal number with a loop?
Example: input "FE" output "254"
I looked at those questions :
How to convert decimal to hex in JavaScript?
Writing a function to convert hex to decimal
Writing a function to convert hex to decimal
Writing a function to convert hex to decimal
How to convert hex to decimal in R
How to convert hex to decimal in c#.net?
And a few more that were not related to JS or loops. I searched for a solution in other languages too in case that I find a way to do it,but I didn't. The first one was the most useful one. Maybe I can devide by 16,compare the result to preset values and print the result, but I want to try with loops. How can I do it?
Maybe you are looking for something like this, knowing that it can be done with a oneliner (with parseInt)?
function hexToDec(hex) {
var result = 0, digitValue;
hex = hex.toLowerCase();
for (var i = 0; i < hex.length; i++) {
digitValue = '0123456789abcdef'.indexOf(hex[i]);
result = result * 16 + digitValue;
}
return result;
}
console.log(hexToDec('FE'));
Alternative
Maybe you want to have a go at using reduce, and ES6 arrow functions:
function hexToDec(hex) {
return hex.toLowerCase().split('').reduce( (result, ch) =>
result * 16 + '0123456789abcdefgh'.indexOf(ch), 0);
}
console.log(hexToDec('FE'));
Just another way to do it...
// The purpose of the function is to convert Hex to Decimal.
// This is done by adding each of the converted values.
function hextoDec(val) {
// Reversed the order because the added values need to 16^i for each value since 'F' is position 1 and 'E' is position 0
var hex = val.split('').reverse().join('');
// Set the Decimal variable as a integer
var dec = 0;
// Loop through the length of the hex to iterate through each character
for (i = 0; i < hex.length; i++) {
// Obtain the numeric value of the character A=10 B=11 and so on..
// you could also change this to var conv = parseInt(hex[i], 16) instead
var conv = '0123456789ABCDEF'.indexOf(hex[i]);
// Calculation performed is the converted value * (16^i) based on the position of the character
// This is then added to the original dec variable. 'FE' for example
// in Reverse order [E] = (14 * (16 ^ 0)) + [F] = (15 * (16 ^ 1))
dec += conv * Math.pow(16, i);
}
// Returns the added decimal value
return dec;
}
console.log(hextoDec('FE'));
Sorry that was backwards, and I can't find where to edit answer, so here is corrected answer:
function doit(hex) {
var num = 0;
for(var x=0;x<hex.length;x++) {
var hexdigit = parseInt(hex[x],16);
num = (num << 4) | hexdigit;
}
return num;
}
If you want to loop over every hex digit, then just loop from end to beginning, shifting each digit 4 bits to the left as you add them (each hex digit is four bits long):
function doit(hex) {
var num = 0;
for(var x=0;x<hex.length;x++) {
var hexdigit = parseInt(hex[x],16);
num = (num << 4) | hexdigit;
}
return num;
}
JavaScript can natively count in hex. I'm finding out the hard way that, in a loop, it converts hex to decimal, so for your purposes, this is great.
prepend your hex with 0x , and you can directly write a for loop.
For example, I wanted get an array of hex values for these unicode characters, but I am by default getting an array of decimal values.
Here's sample code that is converting unicode hex to dec
var arrayOfEmojis = [];
// my range here is in hex format
for (var i=0x1F600; i < 0x1F64F; i++) {
arrayOfEmojis.push('\\u{' + i + '}');
}
console.log(arrayOfEmojis.toString()); // this outputs an array of decimals

Spliting the binary string in half

I am trying to split binary number in half and then just add 4 zeroes.
For example for 10111101 I want to end up with only the first half of the number and make the rest of the number zeroes. What I want to end up would be 10110000.
Can you help me with this?
Use substring to split and then looping to pad
var str = '10111101';
var output = str.substring( 0, str.length/2 );
for ( var counter = 0; counter < str.length/2; counter++ )
{
output += "0";
}
alert(output)
try this (one-liner)
var binary_str = '10111101';
var padded_binary = binary_str.slice(0, binary_str.length/2) + new Array(binary_str.length/2+1).join('0');
console.log([binary_str,padded_binary]);
sample output
['10111101','10110000']
I guess you are using JavaScript...
"10111101".substr(0, 4) + "0000";
It's a bit unclear if you are trying to operate on numbers or strings. The answers already given do a good job of showing how to operate on a strings. If you want to operate with numbers only, you can do something like:
// count the number of leading 0s in a 32-bit word
function nlz32 (word) {
var count;
for (count = 0; count < 32; count ++) {
if (word & (1 << (31 - count))) {
break;
}
}
return count;
}
function zeroBottomHalf (num) {
var digits = 32 - nlz32(num); // count # of digits in num
var half = Math.floor(digits / 2);// how many to set to 0
var lowerMask = (1 << half) - 1; //mask for lower bits: 0b00001111
var upperMask = ~lowerMask //mask for upper bits: 0b11110000
return num & upperMask;
}
var before = 0b10111101;
var after = zeroBottomHalf(before);
console.log('before = ', before.toString(2)); // outputs: 10111101
console.log('after = ', after.toString(2)); // outputs: 10110000
In practice, it is probably simplest to covert your number to a string with num.toString(2), then operate on it like a string as in one of the other answers. At the end you can convert back to a number with parseInt(str, 2)
If you have a real number, not string, then just use binary arithmetic. Assuming your number is always 8 binary digits long - your question is kinda vague on that - it'd be simply:
console.log((0b10111101 & 0b11110000).toString(2))
// 10110000

Converting a 64 bit number string to word array using CryptoJS

I want to know if a string with integer data can be converted to a CryptoJS word array correctly?
Example. Can I convert "175950736337895418" into a word array the same way I can create a word array out of 175950736337895418 (int value).
I have some code that converts integer values to word array
// Converts integer to byte array
function getInt64Bytes( x ){
var bytes = [];
for(var i = 7;i>=0;i--){
bytes[i] = x & 0xff;
x = x>>8;
}
return bytes;
}
//converts the byte array to hex string
function bytesToHexStr(bytes) {
for (var hex = [], i = 0; i < bytes.length; i++) {
hex.push((bytes[i] >>> 4).toString(16));
hex.push((bytes[i] & 0xF).toString(16));
}
return hex.join("");
}
// Main function to convert integer values to word array
function intToWords(counter){
var bytes = getInt64Bytes(counter);
var hexstr = bytesToHexStr(bytes);
var words = CryptoJS.enc.Hex.parse(hexstr);
return words;
}
Even this code doesn't work correctly as very large integer numbers (exceeding javascript limit of numbers 2^53 - 1) get rounded off. Hence I wanted a solution that could take the integer value as string and convert it to a word array correctly.
PS. I need this word array to calculate the HMAC value using the following code
CryptoJS.HmacSHA512(intToWords(counter), CryptoJS.enc.Hex.parse(key))
What you want is to parse big numbers from strings. Since this is necessary for RSA, you can use Tom Wu's JSBN to get that functionality. Be sure to include jsbn.js and jsbn2.js. Then you can use it like this:
function intToWords(num, lengthInBytes) {
var bigInt = new BigInteger();
bigInt.fromString(num, 10); // radix is 10
var hexNum = bigInt.toString(16); // radix is 16
if (lengthInBytes && lengthInBytes * 2 >= hexNum.length) {
hexNum = Array(lengthInBytes * 2 - hexNum.length + 1).join("0") + hexNum;
}
return CryptoJS.enc.Hex.parse(hexNum);
}
var num = "175950736337895418";
numWords = intToWords(num);
document.querySelector("#hexInt").innerHTML = "hexNum: " + numWords.toString();
document.querySelector("#hexIntShort").innerHTML = "hexNumShort: " + intToWords("15646513", 8).toString();
var key = CryptoJS.enc.Hex.parse("11223344ff");
document.querySelector("#result").innerHTML = "hexHMAC: " +
CryptoJS.HmacSHA512(numWords, key).toString();
<script src="https://cdn.rawgit.com/jasondavies/jsbn/master/jsbn.js"></script>
<script src="https://cdn.rawgit.com/jasondavies/jsbn/master/jsbn2.js"></script>
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/hmac-sha512.js"></script>
<div id="hexInt"></div>
<div id="hexIntShort"></div>
<div id="result"></div>
If you need the result in a specific length, then you can pass the number of required bytes as the second argument.

Var overflow in JS and mongo [duplicate]

In JavaScript I would like to create the binary hash of a large boolean array (54 elements) with the following method:
function bhash(arr) {
for (var i = 0, L = arr.length, sum = 0; i < L; sum += Math.pow(2,i)*arr[i++]);
return sum;
}
In short: it creates the smallest integer to store an array of booleans in. Now my problem is that javascript apparently uses floats as default. The maximum number I have to create is 2^54-1 but once javascript reaches 2^53 it starts doing weird things:
9007199254740992+1 = 9007199254740994
Is there any way of using integers instead of floats in javascript? Or large integer summations?
JavaScript uses floating point internally.
What is JavaScript's highest integer value that a number can go to without losing precision?
In other words you can't use more than 53 bits. In some implementations you may be limited to 31.
Try storing the bits in more than one variable, use a string, or get a bignum library, or if you only need to deal with integers, a biginteger library.
BigInt is being added as a native feature of JavaScript.
typeof 123;
// → 'number'
typeof 123n;
// → 'bigint'
Example:
const max = BigInt(Number.MAX_SAFE_INTEGER);
const two = 2n;
const result = max + two;
console.log(result);
// → '9007199254740993'
javascript now has experimental support for BigInt.
At the time of writing only chrome supports this.
caniuse has no entry yet.
BigInt can be either used with a constructor, e.g. BigInt(20) or by appending n, e.g. 20n
Example:
const max = Number.MAX_SAFE_INTEGER;
console.log('javascript Number limit reached', max + 1 === max + 2) // true;
console.log('javascript BigInt limit reached', BigInt(max) + 1n === BigInt(max) + 2n); // false
No. Javascript only has one numeric type. You've to code yourself or use a large integer library (and you cannot even overload arithmetic operators).
Update
This was true in 2010... now (2019) a BigInt library is being standardized and will most probably soon arrive natively in Javascript and it will be the second numeric type present (there are typed arrays, but - at least formally - values extracted from them are still double-precision floating point numbers).
Another implementation of large integer arithmetic (also using BigInt.js) is available at www.javascripter.net/math/calculators/100digitbigintcalculator.htm. Supports the operations + - * / as well as remainder, GCD, LCM, factorial, primality test, next prime, previous prime.
So while attempting one of the leetcode problem I have written a function which takes two numbers in form of string and returns the sum of those numbers in form of string.
(This doesn't work with negative numbers though we can modify this function to cover that)
var addTwoStr = function (s1, s2) {
s1 = s1.split("").reverse().join("")
s2 = s2.split("").reverse().join("")
var carry = 0, rS = '', x = null
if (s1.length > s2.length) {
for (let i = 0; i < s1.length; i++) {
let s = s1[i]
if (i < s2.length) {
x = Number(s) + Number(s2[i]) + carry
rS += String((x % 10))
carry = parseInt(x/10)
} else {
if (carry) {
x = Number(s) + carry
rS += String((x % 10))
carry = parseInt(x/10)
} else {
rS += s
}
}
}
} else {
for (let i = 0; i < s2.length; i++) {
let s = s2[i]
if (i < s1.length) {
x = Number(s) + Number(s1[i]) + carry
rS += String((x % 10))
carry = parseInt(x/10)
} else {
if (carry) {
x = Number(s) + carry
rS += String((x % 10))
carry = parseInt(x/10)
} else {
rS += s
}
}
}
}
if (carry) {
rS += String(carry)
}
return rS.split("").reverse().join("")
}
Example: addTwoStr('120354566', '321442535')
Output: "441797101"
There are various BigInteger Javascript libraries that you can find through googling. e.g. http://www.leemon.com/crypto/BigInt.html
Here's (yet another) wrapper around Leemon Baird's BigInt.js
It is used in this online demo of a big integer calculator in JavaScript which implements the usual four operations + - * /, the modulus (%), and four builtin functions : the square root (sqrt), the power (pow), the recursive factorial (fact) and a memoizing Fibonacci (fibo).
You're probably running into a byte length limit on your system. I'd take the array of booleans, convert it to an array of binary digits ([true, false, true] => [1,0,1]), then join this array into a string "101", then use parseInt('101',2), and you'll have your answer.
/** --if you want to show a big int as your wish use install and require this module
* By using 'big-integer' module is easier to use and handling the big int numbers than regular javascript
* https://www.npmjs.com/package/big-integer
*/
let bigInt = require('big-integer');
//variable: get_bigInt
let get_bigInt = bigInt("999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999");
let arr = [1, 100000, 21, 30, 4, BigInt(999999999999), get_bigInt.value];
console.log(arr[6]); // Output: 999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999n
//Calculation
console.log(arr[6] + 1n); // +1
console.log(arr[6] + 100n); // +100
console.log(arr[6] - 1n); // -1
console.log(arr[6] - 10245n); // -1000n
console.log((arr[6] * 10000n) + 145n - 435n);

Categories