Skip to content

Commit f876320

Browse files
Merge pull request #20 from yoshinani-dev/feature/auto-id
feat: autoIdを追加
2 parents 6421413 + 8368d2a commit f876320

3 files changed

Lines changed: 31 additions & 0 deletions

File tree

.changeset/olive-hands-draw.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@yoshinani/utils': minor
3+
---
4+
5+
autoId を追加

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
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",

src/auto-id/index.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
}

0 commit comments

Comments
 (0)