dragonroll/backend/node_modules/nanoid/async/index.browser.js

38 lines
1.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// This file replaces `async/index.js` in bundlers like webpack or Rollup,
// according to `browser` config in `package.json`.
var crypto = self.crypto || self.msCrypto
// This alphabet uses a-z A-Z 0-9 _- symbols.
// Symbols are generated for smaller size.
// -_zyxwvutsrqponmlkjihgfedcba9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA
var url = '-_'
// Loop from 36 to 0 (from z to a and 9 to 0 in Base36).
var i = 36
while (i--) {
// 36 is radix. Number.prototype.toString(36) returns number
// in Base36 representation. Base36 is like hex, but it uses 09 and a-z.
url += i.toString(36)
}
// Loop from 36 to 10 (from Z to A in Base36).
i = 36
while (i-- - 10) {
url += i.toString(36).toUpperCase()
}
module.exports = function (size) {
var id = ''
var bytes = crypto.getRandomValues(new Uint8Array(size || 21))
i = size || 21
// Compact alternative for `for (var i = 0; i < size; i++)`
while (i--) {
// We cant use bytes bigger than the alphabet. 63 is 00111111 bitmask.
// This mask reduces random byte 0-255 to 0-63 values.
// There is no need in `|| ''` and `* 1.6` hacks in here,
// because bitmask trim bytes exact to alphabet size.
id += url[bytes[i] & 63]
}
return Promise.resolve(id)
}