You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.2 KiB

/**
* Secure random string generator with custom alphabet.
*
* Alphabet must contain 256 symbols or less. Otherwise, the generator
* will not be secure.
*
* @param {generator} random The random bytess generator.
* @param {string} alphabet Symbols to be used in new random string.
* @param {size} size The number of symbols in new random string.
*
* @return {string} Random string.
*
* @example
* var format = require('nanoid/format')
*
* function random (size) {
* var result = []
* for (var i = 0; i < size; i++) result.push(randomByte())
* return result
* }
*
* format(random, "abcdef", 5) //=> "fbaef"
*
* @name format
*/
module.exports = function (random, alphabet, size) {
var mask = (2 << Math.log(alphabet.length - 1) / Math.LN2) - 1
var step = Math.ceil(1.6 * mask * size / alphabet.length)
var id = ''
while (true) {
var bytes = random(step)
for (var i = 0; i < step; i++) {
var byte = bytes[i] & mask
if (alphabet[byte]) {
id += alphabet[byte]
if (id.length === size) return id
}
}
}
}
/**
* @callback generator
* @param {number} bytes The number of bytes to generate.
* @return {number[]} Random bytes.
*/