slightly improves performance in randBits()

- only calculates (bitLength % 8) once
 - uses const where possible
This commit is contained in:
Coffee Converter 2020-03-24 15:53:31 -05:00
parent 36d9786b3d
commit 155dd49434
1 changed files with 5 additions and 4 deletions

View File

@ -400,13 +400,14 @@ export function randBits(bitLength, forceLength = false) {
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
const byteLength = Math.ceil(bitLength / 8);
let rndBytes = randBytesSync(byteLength, false);
if (bitLength % 8) {
const rndBytes = randBytesSync(byteLength, false);
const bitLengthMod8 = bitLength % 8;
if (bitLengthMod8) {
// Fill with 0's the extra bits
rndBytes[0] = rndBytes[0] & (2 ** (bitLength % 8) - 1);
rndBytes[0] = rndBytes[0] & (2 ** bitLengthMod8 - 1);
}
if (forceLength) {
let mask = (bitLength % 8) ? 2 ** ((bitLength % 8) - 1) : 128;
const mask = bitLengthMod8 ? 2 ** (bitLengthMod8 - 1) : 128;
rndBytes[0] = rndBytes[0] | mask;
}
return rndBytes;