UNPKG

740 BJavaScriptView Raw
1/**
2 * Generate URL-friendly unique ID. This method use non-secure predictable
3 * random generator with bigger collision probability.
4 *
5 * @param {string} alphabet Symbols to be used in ID.
6 * @param {number} [size=21] The number of symbols in ID.
7 *
8 * @return {string} Random string.
9 *
10 * @example
11 * const nanoid = require('nanoid/non-secure')
12 * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
13 *
14 * @name nonSecure
15 * @function
16 */
17module.exports = function (alphabet, size) {
18 size = size || 21
19 var id = ''
20 // Compact alternative for `for (var i = 0; i < size; i++)`
21 while (size--) {
22 // `| 0` is compact and faster alternative for `Math.floor()`
23 id += alphabet[Math.random() * alphabet.length | 0]
24 }
25 return id
26}