Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Incorporate math-random-polyfill.js for better Math.random().
- Loading branch information
1 parent
2b91eb4
commit 81b7c27
Showing
4 changed files
with
40 additions
and
6 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// math-random-polyfill.js | ||
// https://github.com/DavidAnson/math-random-polyfill | ||
// 2016-12-03 | ||
|
||
(function iife () { | ||
"use strict"; | ||
// Feature detection | ||
var crypto = window.crypto || window.msCrypto; | ||
if (window.Uint32Array && crypto && crypto.getRandomValues) { | ||
// Capture functions and values | ||
var Math_random = Math.random.bind(Math); | ||
var crypto_getRandomValues = crypto.getRandomValues.bind(crypto); | ||
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; | ||
var highShift = Math.pow(2, 32); | ||
var highMask = Math.pow(2, 53 - 32) - 1; | ||
// Polyfill Math.random | ||
Math.random = function math_random_polyfill () { | ||
try { | ||
// Get random bits for numerator | ||
var array = new Uint32Array(2); | ||
crypto_getRandomValues(array); | ||
var numerator = ((array[0] & highMask) * highShift) + array[1]; | ||
// Divide by maximum-value denominator | ||
var denominator = MAX_SAFE_INTEGER + 1; | ||
return numerator / denominator; | ||
} catch (ex) { | ||
// Exception in crypto.getRandomValues, fall back to Math.random | ||
return Math_random(); | ||
} | ||
}; | ||
} | ||
}()); |
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