format.js
This file
Path
format.js
50 lines · 1.2 KiB · JavaScript
Last changed by
Use ES6 in examplesAndrey Sitnikbefore adoption433f14d
History of this fileTake it
The walk stopped after 200 commits: lines older than c59016d point at it.
Add bytes to package descriptionAndrey Sitnikbefore adoptionc59016d
lines 1–6why, one step back1/**2 * Secure random string generator with custom alphabet.3 *4 * Alphabet must contain 256 symbols or less. Otherwise, the generator5 * will not be secure.6 *Fix nanoid.format JSDocAndrey Sitnikbefore adoptioneb3d04f
line 7why, one step back7 * @param {generator} random The random bytes generator.Add bytes to package descriptionAndrey Sitnikbefore adoptionc59016d
lines 8–13why, one step back8 * @param {string} alphabet Symbols to be used in new random string.9 * @param {size} size The number of symbols in new random string.10 *11 * @return {string} Random string.12 *13 * @exampleUse ES6 in examplesAndrey Sitnikbefore adoption433f14d
line 14why, one step back14 * const format = require('nanoid/format')Add bytes to package descriptionAndrey Sitnikbefore adoptionc59016d
lines 15–16why, one step back15 *16 * function random (size) {Use ES6 in examplesAndrey Sitnikbefore adoption433f14d
lines 17–20why, one step back17 * const result = []18 * for (let i = 0; i < size; i++) {19 * result.push(randomByte())20 * }Add bytes to package descriptionAndrey Sitnikbefore adoptionc59016d
lines 21–26why, one step back21 * return result22 * }23 *24 * format(random, "abcdef", 5) //=> "fbaef"25 *26 * @name formatFix JSDocAndrey Sitnikbefore adoption8e101a3
line 27why, one step back27 * @functionAdd bytes to package descriptionAndrey Sitnikbefore adoptionc59016d
lines 28–29why, one step back28 */29module.exports = function (random, alphabet, size) {Calculate mask based on alphabet length (#29)Anton Khlynovskiybefore adoption3e641fe
line 30why, one step back30 var mask = (2 << Math.log(alphabet.length - 1) / Math.LN2) - 1Add bytes to package descriptionAndrey Sitnikbefore adoptionc59016d
lines 31–50why, one step back31 var step = Math.ceil(1.6 * mask * size / alphabet.length)3233 var id = ''34 while (true) {35 var bytes = random(step)36 for (var i = 0; i < step; i++) {37 var byte = bytes[i] & mask38 if (alphabet[byte]) {39 id += alphabet[byte]40 if (id.length === size) return id41 }42 }43 }44}4546/**47 * @callback generator48 * @param {number} bytes The number of bytes to generate.49 * @return {number[]} Random bytes.50 */