UNPKG

1.02 kBJavaScriptView Raw
1var random = require('./random')
2var url = require('../url')
3
4/**
5 * Generate secure URL-friendly unique ID. Non-blocking version.
6 *
7 * By default, ID will have 21 symbols to have a collision probability similar
8 * to UUID v4.
9 *
10 * @param {number} [size=21] The number of symbols in ID.
11 *
12 * @return {Promise} Promise with random string.
13 *
14 * @example
15 * const nanoidAsync = require('nanoid/async')
16 * nanoidAsync.then(id => {
17 * model.id = id
18 * })
19 *
20 * @name async
21 * @function
22 */
23module.exports = function (size) {
24 size = size || 21
25 return random(size).then(function (bytes) {
26 var id = ''
27 // Compact alternative for `for (var i = 0; i < size; i++)`
28 while (size--) {
29 // We can’t use bytes bigger than the alphabet. 63 is 00111111 bitmask.
30 // This mask reduces random byte 0-255 to 0-63 values.
31 // There is no need in `|| ''` and `* 1.6` hacks in here,
32 // because bitmask trim bytes exact to alphabet size.
33 id += url[bytes[size] & 63]
34 }
35 return id
36 })
37}