From 155dd49434d5bca144a9ab338f0bb7ef7a6ec8b7 Mon Sep 17 00:00:00 2001 From: Coffee Converter Date: Tue, 24 Mar 2020 15:53:31 -0500 Subject: [PATCH] slightly improves performance in randBits() - only calculates (bitLength % 8) once - uses const where possible --- src/main.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main.js b/src/main.js index 795a953..f3c8656 100644 --- a/src/main.js +++ b/src/main.js @@ -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;