Node.jsでランダムな文字列を生成する関数です。
36文字種
-
length
で与えた長さの文字列を生成する。 - 生成される文字列は
/[0-9a-z]*/
。 - このアルゴリズムにはバイアスがあり、0〜4が多めに出現するので、厳密なランダムではない。
const {randomBytes} = require('crypto')
function generateRandomString(length) {
return randomBytes(length).reduce((p, i) => p + (i % 36).toString(36), '')
}
32文字種
-
length
で与えた長さの文字列を生成する。 - 生成される文字列は
/[0-9a-v]*/
。 - ランダムな0-256を32でモジュロ演算しているので、一応文字ごとの確率は均等なはず。
const {randomBytes} = require('crypto')
function generateRandomString(length) {
return randomBytes(length).reduce((p, i) => p + (i % 32).toString(32), '')
}
Base32風の文字種
-
length
で与えた長さの文字列を生成する。 - 生成される文字種は32種類。
- すべて大文字。
- OやIと見た目が似てる0や1がない。
/[2-7A-Z]*/
- ランダムな0-256を32でモジュロ演算しているので、一応文字ごとの確率は均等なはず。
const {randomBytes} = require('crypto')
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.split('')
function generateRandomString(length) {
return randomBytes(length).reduce((p, i) => p + chars[(i % 32)], '')
}