File tree Expand file tree Collapse file tree 1 file changed +12
-2
lines changed Expand file tree Collapse file tree 1 file changed +12
-2
lines changed Original file line number Diff line number Diff line change 14
14
* limitations under the License.
15
15
*/
16
16
17
+ import { randomBytes } from 'crypto' ;
17
18
import { GoogleError , ServiceConfig , Status } from 'google-gax' ;
18
19
19
20
import { DocumentData } from './types' ;
@@ -52,8 +53,17 @@ export function autoId(): string {
52
53
const chars =
53
54
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' ;
54
55
let autoId = '' ;
55
- for ( let i = 0 ; i < 20 ; i ++ ) {
56
- autoId += chars . charAt ( Math . floor ( Math . random ( ) * chars . length ) ) ;
56
+ while ( autoId . length < 20 ) {
57
+ const bytes = randomBytes ( 40 ) ;
58
+ bytes . forEach ( b => {
59
+ // Length of `chars` is 62. We only take bytes between 0 and 62*4-1
60
+ // (both inclusive). The value is then evenly mapped to indices of `char`
61
+ // via a modulo operation.
62
+ const maxValue = 62 * 4 - 1 ;
63
+ if ( autoId . length < 20 && b <= maxValue ) {
64
+ autoId += chars . charAt ( b % 62 ) ;
65
+ }
66
+ } ) ;
57
67
}
58
68
return autoId ;
59
69
}
You can’t perform that action at this time.
0 commit comments