Skip to content

Instantly share code, notes, and snippets.

@jcward
Last active July 22, 2018 16:50
Show Gist options
  • Select an option

  • Save jcward/ed4a3f7a93f4aa17d4634be9559842b1 to your computer and use it in GitHub Desktop.

Select an option

Save jcward/ed4a3f7a93f4aa17d4634be9559842b1 to your computer and use it in GitHub Desktop.
Quick Math.random() wrapper with support for window.crypto.getRandomValues
// Math.random() wrapper with support for window.crypto.getRandomValues
// return a random number, 0 <= rand() < 1
function rand() {
if (window.crypto && window.crypto.getRandomValues && (typeof Uint8Array=='function')) {
var buf = new Uint8Array(4);
window.crypto.getRandomValues(buf);
// buf = [0,0,0,0]; // 0
// buf = [255,255,255,255]; // closest to 1
// buf = [0,0,0,128]; // < 0.5
// buf = [1,0,0,128]; // > 0.5
var v = ((buf[3]<<24) | (buf[2]<<16) | (buf[1]<<8) | buf[0])/0xffffffff;
return v<0 ? v+1 : v;
} else {
return Math.random();
}
}
// Minified:
// function rand(){if(window.crypto&&window.crypto.getRandomValues&&"function"==typeof Uint8Array){var A=new Uint8Array(4);window.crypto.getRandomValues(A);var o=(A[3]<<24|A[2]<<16|A[1]<<8|A[0])/0xffffffff;return 0>o?o+1:o}return Math.random()}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment