Skip to content
Myr

format.js

This file

Path

async/format.js

55 lines · 1.4 KiB · JavaScript

Last changed by

Decrease async/format sizeAndrey Sitnikbefore adoptione925161

History of this file

Take it

Add async random, generate, and formatAndrey Sitnikbefore adoption64017de

lines 1–6why, one step back
1/**
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 JSDocAndrey Sitnikbefore adoption691b5bb

line 7why, one step back
7 * @param {asyncGenerator} random The random bytes generator.

Add async random, generate, and formatAndrey Sitnikbefore adoption64017de

lines 8–34why, one step back
8 * @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 {Promise} Promise with random string.12 *13 * @example14 * const formatAsync = require('nanoid/async/format')15 *16 * function random (size) {17 * const result = []18 * for (let i = 0; i < size; i++) {19 * result.push(randomByte())20 * }21 * return Promise.resolve(result)22 * }23 *24 * formatAsync(random, "abcdef", 5).then(id => {25 * model.id = id //=> "fbaef"26 * })27 *28 * @name formatAsync29 * @function30 */31module.exports = function (random, alphabet, size) {32 var mask = (2 << Math.log(alphabet.length - 1) / Math.LN2) - 133 var step = Math.ceil(1.6 * mask * size / alphabet.length)34

Decrease async/format sizeAndrey Sitnikbefore adoptione925161

lines 35–41why, one step back
35 function tick (id) {
36 return random(step).then(function (bytes) {37 for (var i = 0; i < step; i++) {38 var byte = bytes[i] & mask39 if (alphabet[byte]) {40 id += alphabet[byte]41 if (id.length === size) return id

Add async random, generate, and formatAndrey Sitnikbefore adoption64017de

line 42why, one step back
42 }

Decrease async/format sizeAndrey Sitnikbefore adoptione925161

lines 43–48why, one step back
43 }
44 return tick(id)45 })46 }4748 return tick('')

Add async random, generate, and formatAndrey Sitnikbefore adoption64017de

lines 49–51why, one step back
49}
5051/**

Fix JSDocAndrey Sitnikbefore adoption691b5bb

line 52why, one step back
52 * @callback asyncGenerator

Add async random, generate, and formatAndrey Sitnikbefore adoption64017de

line 53why, one step back
53 * @param {number} bytes The number of bytes to generate.

Fix JSDocAndrey Sitnikbefore adoption691b5bb

line 54why, one step back
54 * @return {Promise} Promise with array of random bytes.

Add async random, generate, and formatAndrey Sitnikbefore adoption64017de

line 55why, one step back
55 */