Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/olive-hands-draw.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@yoshinani/utils': minor
---

autoId を追加
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"tsc": "tsc --noEmit"
},
"exports": {
"./auto-id": "./dist/auto-id/index.js",
"./date": "./dist/date/index.js",
"./file": "./dist/file/index.js",
"./string": "./dist/string/index.js",
Expand Down
25 changes: 25 additions & 0 deletions src/auto-id/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Firestoreが自動生成するものと同じ20文字のランダムなIDを生成する
* @see https://github.com/firebase/firebase-js-sdk/blob/6e0e303173c93646c07b9138c7bed8749b514e8f/packages/firestore/src/util/misc.ts#L34
* @returns ランダムなID
*/
export function autoId(): string {
// 英数字
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
// `char.length` の倍数で最大の値
const maxMultiple = Math.floor(256 / chars.length) * chars.length

let autoId = ""
const targetLength = 20
while (autoId.length < targetLength) {
const bytes = crypto.getRandomValues(new Uint8Array(40))
bytes.forEach((byte) => {
// [0, maxMultiple) の値のみを受け取ることで、`chars` に均等にマッピングできるようにする
if (autoId.length < targetLength && byte < maxMultiple) {
autoId += chars.charAt(byte % chars.length)
}
})
}

return autoId
}