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+ ---
2+ ' @yoshinani/utils ' : minor
3+ ---
4+
5+ autoId を追加
Original file line number Diff line number Diff line change 3333 "tsc" : " tsc --noEmit"
3434 },
3535 "exports" : {
36+ "./auto-id" : " ./dist/auto-id/index.js" ,
3637 "./date" : " ./dist/date/index.js" ,
3738 "./file" : " ./dist/file/index.js" ,
3839 "./string" : " ./dist/string/index.js" ,
Original file line number Diff line number Diff line change 1+ /**
2+ * Firestoreが自動生成するものと同じ20文字のランダムなIDを生成する
3+ * @see https://github.com/firebase/firebase-js-sdk/blob/6e0e303173c93646c07b9138c7bed8749b514e8f/packages/firestore/src/util/misc.ts#L34
4+ * @returns ランダムなID
5+ */
6+ export function autoId ( ) : string {
7+ // 英数字
8+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
9+ // `char.length` の倍数で最大の値
10+ const maxMultiple = Math . floor ( 256 / chars . length ) * chars . length
11+
12+ let autoId = ""
13+ const targetLength = 20
14+ while ( autoId . length < targetLength ) {
15+ const bytes = crypto . getRandomValues ( new Uint8Array ( 40 ) )
16+ bytes . forEach ( ( byte ) => {
17+ // [0, maxMultiple) の値のみを受け取ることで、`chars` に均等にマッピングできるようにする
18+ if ( autoId . length < targetLength && byte < maxMultiple ) {
19+ autoId += chars . charAt ( byte % chars . length )
20+ }
21+ } )
22+ }
23+
24+ return autoId
25+ }
You can’t perform that action at this time.
0 commit comments