File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- import { randomInt } from 'node:crypto' ;
2-
31declare global {
42 interface String {
53 format : ( ...args : Array < any > ) => string ;
@@ -13,9 +11,21 @@ declare global {
1311
1412const defaultDict = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' ;
1513
14+ function randomInt ( min : number , max : number ) {
15+ const range = max - min + 1 ;
16+ const maxValid = Math . floor ( 4294967296 / range ) * range ;
17+ const array = new Uint32Array ( 1 ) ;
18+ let value : number ;
19+ do {
20+ crypto . getRandomValues ( array ) ;
21+ value = array [ 0 ] ;
22+ } while ( value >= maxValid ) ;
23+ return min + ( value % range ) ;
24+ }
25+
1626export function randomstring ( digit = 32 , dict = defaultDict ) {
1727 let str = '' ;
18- for ( let i = 1 ; i <= digit ; i ++ ) str += dict [ randomInt ( dict . length ) ] ;
28+ for ( let i = 1 ; i <= digit ; i ++ ) str += dict [ randomInt ( 0 , dict . length - 1 ) ] ;
1929 return str ;
2030}
2131
You can’t perform that action at this time.
0 commit comments