Last active
August 29, 2015 14:23
-
-
Save gabalafou/51264596a4f16755b8ea to your computer and use it in GitHub Desktop.
window.crypto random int [0, 99] untested unused function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Returns a random integer in the range [0, 99] | |
function getBucketInt() { | |
try { | |
var random; | |
// inside try-block because Uint8Array does | |
// not have wide browser support | |
var ab = new Uint8Array(1); | |
// note: 10 is arbitrary loop limit - | |
// just want to have 100% guarantee | |
// that this loop will end - there is | |
// still some probability that even after | |
// 10 loops, you'll get a value in [200, 255] | |
// thus slightly biasing buckets in [0, 55] | |
for (var i = 0; i < 10; i++) { | |
// inside try-block because crypto does | |
// not have wide browser support | |
crypto.getRandomValues(ab); | |
random = ab[0]; | |
if (random < 200) | |
break; | |
} | |
return random % 100; | |
} catch (e) { | |
return Math.floor(Math.random() * 100); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment