-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
43 lines (39 loc) · 832 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var random = require('./random')
var url = require('./url')
/**
* Generate secure URL-friendly unique ID.
*
* By default, ID will have 21 symbols to have a collision probability similar
* to UUID v4.
*
* @param {number} [size=21] The number of symbols in ID.
*
* @return {string} Random string.
*
* @example
* const nanoid = require('nanoid')
* model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
*
* @name nanoid
* @function
*/
module.exports = function (size, attempt) {
size = size || 21
var bytes
try {
bytes = random(size)
} catch (e) {
if (typeof attempt === 'undefined') attempt = 3
attempt -= 1
if (attempt === 0) {
throw e
} else {
return module.exports(size, attempt)
}
}
var id = ''
while (0 < size--) {
id += url[bytes[size] & 63]
}
return id
}