Skip to content

Instantly share code, notes, and snippets.

@lac5
Created May 24, 2021 17:00
Show Gist options
  • Save lac5/5b7132ac4f6c8b65910f23d7f7b6c704 to your computer and use it in GitHub Desktop.
Save lac5/5b7132ac4f6c8b65910f23d7f7b6c704 to your computer and use it in GitHub Desktop.
export default function randomBigInt(max) {
const segment = Number.MAX_SAFE_INTEGER;
const bigSegment = BigInt(segment);
const maxArray = [];
for (let bigMax = BigInt(max), zero = 0n; bigMax > zero; bigMax /= bigSegment) {
maxArray.unshift(Number(bigMax % bigSegment));
}
const superSum = (a, b) => a * bigSegment + b;
return function() {
let unlimited = false;
return maxArray.map(n => {
let result;
if (unlimited) {
result = Math.floor(Math.random() * segment);
} else {
result = Math.floor(Math.random() * n);
if (result < n) {
unlimited = true;
}
}
return BigInt(result);
}).reduce(superSum, 0n);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment