EN
JavaScript - generate random long value as string (without BigInt usage)
8 points
In this short article, we would like to show how in simple way generate random long value as string using JavaScript.
Note: as long value we understand signed 64 bits integer value (from
-9223372036854775808
to9223372036854775807
).
Quick solution:
xxxxxxxxxx
1
const randomNumber = (min, max) => {
2
const scope = max - min + 1;
3
return Math.floor(min + scope * Math.random());
4
};
5
6
const randomString = (min, max, length = 0) => {
7
let text = String(randomNumber(min, max));
8
for (let i = text.length; i < length; ++i) {
9
text = '0' + text;
10
}
11
return text;
12
};
13
14
const randomLong = () => {
15
//
16
// - 922337203685477 5808 <--- min long value (int64)
17
// + 922337203685477 5807 <--- max long value (int64)
18
// AAAAAAAAAAAAAAA BBBB
19
//
20
// A - part 1
21
// B - part 2
22
//
23
const a = randomNumber(-922337203685477, +922337203685477);
24
if (a < 0) {
25
return a + randomString(0, a > -922337203685477 ? 10000 : 5808, 4);
26
} else {
27
return a + randomString(0, a < +922337203685477 ? 10000 : 5807, 4);
28
}
29
};
30
31
32
// Usage example:
33
34
console.log(randomLong()); // -6733751053698669900
35
console.log(randomLong()); // -682370853513783837
36
console.log(randomLong()); // 5592452255720332045
Note: the above solution doesn't use
BigInt
type that makes it working in the older JavaScript engines.