4 ms·
Wait so `%` is bad but `& 63` is fine? Ain't you doing a mod as well??? It's just that you have power of two (64 in this case) that you are trying to exploit he
by maxpert 9y ago
Wait so `%` is bad but `& 63` is fine? Ain't you doing a mod as well??? It's just that you have power of two (64 in this case) that you are trying to exploit here... anyone who knows basics of computer science can tell you it's same!
If it's about reducing code size I can demonstrate smaller code:
module.exports = function (size) {
return random(size || 22)
.map(r => url[r & 63])
.join('');
};
I am always disappointed to see these kind of packages, as mentioned somewhere in comments above
> It is noticable again and again that devs publishing to npm are not up to snuff, I wish I knew why, as this does not happen with other dynamic languages/their code repos.
And I totally agree!
- deleted 9y ago[deleted]
- dchest 9y agoCheck the code below: var masks = [15, 31, 63, 127, 255] ... var mask = masks.find(function (i) { return i >= alphabet.length - 1 }) ... var byte = bytes[i] & mask if (alphabet[byte]) { id += alphabet[byte] Masking results in a random uniform number that is a power of two and greater or equal than the alphabet length and then indexes that are greater than alphabet length are rejected, which is a common way of avoiding modulo bias. I am always disappointed to see these kind of packages, as mentioned somewhere in comments above Because you didn't understand how it worked and assumed that it's bad?
- daveFNbuck 9y agoI believe the criticism here is about index.js, which is what all the other claims are about. var bytes = random(size) for (var i = 0; i < size; i++) { id += url[bytes[i] & 63] } This part of the code just uses an alphabet size of 64, which makes the approach actually used in the exported function identical to modding the byte by the alphabet size.
- dchest 9y agoYes, with a power-of-two alphabet length there's no bias. The poster seems to be confused about modulo bias claims, which apply to non-power-of-two alphabets, not a particular way of calculating modulus.
- deleted 9y ago[deleted]
- deleted 9y ago[deleted]