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:
// ONLINE-RUNNER:browser;
const randomNumber = (min, max) => {
const scope = max - min + 1;
return Math.floor(min + scope * Math.random());
};
const randomString = (min, max, length = 0) => {
let text = String(randomNumber(min, max));
for (let i = text.length; i < length; ++i) {
text = '0' + text;
}
return text;
};
const randomLong = () => {
//
// - 922337203685477 5808 <--- min long value (int64)
// + 922337203685477 5807 <--- max long value (int64)
// AAAAAAAAAAAAAAA BBBB
//
// A - part 1
// B - part 2
//
const a = randomNumber(-922337203685477, +922337203685477);
if (a < 0) {
return a + randomString(0, a > -922337203685477 ? 10000 : 5808, 4);
} else {
return a + randomString(0, a < +922337203685477 ? 10000 : 5807, 4);
}
};
// Usage example:
console.log(randomLong()); // -6733751053698669900
console.log(randomLong()); // -682370853513783837
console.log(randomLong()); // 5592452255720332045
Note: the above solution doesn't use
BigInt
type that makes it working in the older JavaScript engines.