Skip to content

Commit f4e7325

Browse files
authored
reduce bundlesize by moving from while to reduce (#355)
* reduce bundlesize by moving from while to reduce * reduce bundlesize for brotli by symbols reusing
1 parent cb3053e commit f4e7325

File tree

3 files changed

+12
-17
lines changed

3 files changed

+12
-17
lines changed

index.browser.js

+8-13
Original file line numberDiff line numberDiff line change
@@ -47,31 +47,26 @@ let customRandom = (alphabet, defaultSize, getRandom) => {
4747
let customAlphabet = (alphabet, size = 21) =>
4848
customRandom(alphabet, size, random)
4949

50-
let nanoid = (size = 21) => {
51-
let id = ''
52-
let bytes = crypto.getRandomValues(new Uint8Array(size))
53-
54-
// A compact alternative for `for (var i = 0; i < step; i++)`.
55-
while (size--) {
50+
let nanoid = (size = 21) =>
51+
crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
5652
// It is incorrect to use bytes exceeding the alphabet size.
5753
// The following mask reduces the random byte in the 0-255 value
5854
// range to the 0-63 value range. Therefore, adding hacks, such
5955
// as empty string fallback or magic numbers, is unneccessary because
6056
// the bitmask trims bytes down to the alphabet size.
61-
let byte = bytes[size] & 63
57+
byte &= 63
6258
if (byte < 36) {
6359
// `0-9a-z`
6460
id += byte.toString(36)
6561
} else if (byte < 62) {
6662
// `A-Z`
6763
id += (byte - 26).toString(36).toUpperCase()
68-
} else if (byte < 63) {
69-
id += '_'
70-
} else {
64+
} else if (byte > 62) {
7165
id += '-'
66+
} else {
67+
id += '_'
7268
}
73-
}
74-
return id
75-
}
69+
return id
70+
}, '')
7671

7772
module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }

nanoid.js

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "nanoid",
33
"version": "3.3.2",
4-
"description": "A tiny (130 bytes), secure URL-friendly unique string ID generator",
4+
"description": "A tiny (116 bytes), secure URL-friendly unique string ID generator",
55
"keywords": [
66
"uuid",
77
"random",
@@ -68,7 +68,7 @@
6868
{
6969
"name": "nanoid",
7070
"import": "{ nanoid }",
71-
"limit": "130 B"
71+
"limit": "116 B"
7272
},
7373
{
7474
"name": "customAlphabet",
@@ -108,7 +108,7 @@
108108
"name": "Brotli all",
109109
"brotli": true,
110110
"import": "{ nanoid, customAlphabet, urlAlphabet }",
111-
"limit": "271 B"
111+
"limit": "260 B"
112112
},
113113
{
114114
"name": "Brotli non-secure",

0 commit comments

Comments
 (0)