main
Last change
on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago |
Update repo after prototype presentation
|
-
Property mode
set to
100644
|
File size:
1.0 KB
|
Line | |
---|
1 | let { urlAlphabet } = require('./url-alphabet/index.cjs')
|
---|
2 | let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
|
---|
3 | let customRandom = (alphabet, defaultSize, getRandom) => {
|
---|
4 | let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
|
---|
5 | let step = -~((1.6 * mask * defaultSize) / alphabet.length)
|
---|
6 | return (size = defaultSize) => {
|
---|
7 | let id = ''
|
---|
8 | while (true) {
|
---|
9 | let bytes = getRandom(step)
|
---|
10 | let j = step
|
---|
11 | while (j--) {
|
---|
12 | id += alphabet[bytes[j] & mask] || ''
|
---|
13 | if (id.length === size) return id
|
---|
14 | }
|
---|
15 | }
|
---|
16 | }
|
---|
17 | }
|
---|
18 | let customAlphabet = (alphabet, size = 21) =>
|
---|
19 | customRandom(alphabet, size, random)
|
---|
20 | let nanoid = (size = 21) =>
|
---|
21 | crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
|
---|
22 | byte &= 63
|
---|
23 | if (byte < 36) {
|
---|
24 | id += byte.toString(36)
|
---|
25 | } else if (byte < 62) {
|
---|
26 | id += (byte - 26).toString(36).toUpperCase()
|
---|
27 | } else if (byte > 62) {
|
---|
28 | id += '-'
|
---|
29 | } else {
|
---|
30 | id += '_'
|
---|
31 | }
|
---|
32 | return id
|
---|
33 | }, '')
|
---|
34 | module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.