get-random-values-polypony
Version:
Synchronous randombytes function that works in node, the browser & react-native!
2 lines • 1.34 kB
JavaScript
const MAX_SIZE=65536;let base,getRandomValues,polyfill;if(window.msCrypto||!!window.StyleMedia){base=window.msCrypto||window.crypto;const randomValues=base.getRandomValues;getRandomValues=function(input){return input instanceof Uint8ClampedArray?randomValues.call(base,new Uint8Array(input.buffer,input.byteOffset,input.byteLength)):randomValues.call(base,input),input},polyfill=function(){window.crypto||(window.crypto={}),window.crypto.getRandomValues!==getRandomValues&&(window.crypto._getRandomValues=window.crypto.getRandomValues,window.crypto.getRandomValues=getRandomValues)}}else base=window.crypto,polyfill=function(){},getRandomValues=base.getRandomValues;function getRandomValuesBrowser(input){var _Mathmin=Math.min;const n=input.byteLength,offset=input.byteOffset,buffer=input.buffer;if(n<=MAX_SIZE)getRandomValues.call(base,input instanceof Float32Array||input instanceof Float64Array||input instanceof DataView||window.BigInt64Array&&(input instanceof window.BigInt64Array||input instanceof window.BigUint64Array)?new Uint8Array(buffer,offset,n):input);else for(let i=0;i<n;i+=MAX_SIZE)getRandomValues.call(base,new Uint8Array(buffer,i+offset,_Mathmin(n-i,MAX_SIZE)));return input}// IE 11
getRandomValuesBrowser.name="getRandomValuesBrowser",getRandomValuesBrowser.polyfill=polyfill,module.exports=getRandomValuesBrowser;