Skip to content

Commit

Permalink
feat(random): add randomBytes() wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 26, 2020
1 parent df87b7c commit c536bcd
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/random/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ export * from "./xorshift128";
export * from "./xorwow";
export * from "./xsadd";

export * from "./random-bytes";
export * from "./random-id";
export * from "./weighted-random";
17 changes: 17 additions & 0 deletions packages/random/src/random-bytes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { hasCrypto } from "@thi.ng/checks";
import { SYSTEM } from "./system";

/**
* Fills given byte array with random values. Wrapper for
* `crypto.getRandomValues()` with automatic fallback to using
* `Math.random` if platform doesn't provide global crypto instance.
*/
export const randomBytes = hasCrypto()
? (buf: Uint8Array) => window.crypto.getRandomValues(buf)
: (buf: Uint8Array) => {
const n = buf.length;
for (let i = 0; i < n; i++) {
buf[i] = SYSTEM.int() & 0xff;
}
return buf;
};

0 comments on commit c536bcd

Please sign in to comment.