UNPKG

927 BJavaScriptView Raw
1var random = require('./random')
2var url = require('./url')
3
4/**
5 * Generate secure URL-friendly unique ID.
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 {string} Random string.
13 *
14 * @example
15 * const nanoid = require('nanoid')
16 * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
17 *
18 * @name nanoid
19 * @function
20 */
21module.exports = function (size) {
22 size = size || 21
23 var bytes = random(size)
24 var id = ''
25 // Compact alternative for `for (var i = 0; i < size; i++)`
26 while (size--) {
27 // We can’t use bytes bigger than the alphabet. 63 is 00111111 bitmask.
28 // This mask reduces random byte 0-255 to 0-63 values.
29 // There is no need in `|| ''` and `* 1.6` hacks in here,
30 // because bitmask trim bytes exact to alphabet size.
31 id += url[bytes[size] & 63]
32 }
33 return id
34}