Skip to content

Commit

Permalink
reduce bundlesize by moving from while to reduce (#355)
Browse files Browse the repository at this point in the history
* reduce bundlesize by moving from while to reduce

* reduce bundlesize for brotli by symbols reusing
  • Loading branch information
artalar authored Apr 18, 2022
1 parent cb3053e commit f4e7325
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 17 deletions.
21 changes: 8 additions & 13 deletions index.browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,31 +47,26 @@ let customRandom = (alphabet, defaultSize, getRandom) => {
let customAlphabet = (alphabet, size = 21) =>
customRandom(alphabet, size, random)

let nanoid = (size = 21) => {
let id = ''
let bytes = crypto.getRandomValues(new Uint8Array(size))

// A compact alternative for `for (var i = 0; i < step; i++)`.
while (size--) {
let nanoid = (size = 21) =>
crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
// It is incorrect to use bytes exceeding the alphabet size.
// The following mask reduces the random byte in the 0-255 value
// range to the 0-63 value range. Therefore, adding hacks, such
// as empty string fallback or magic numbers, is unneccessary because
// the bitmask trims bytes down to the alphabet size.
let byte = bytes[size] & 63
byte &= 63
if (byte < 36) {
// `0-9a-z`
id += byte.toString(36)
} else if (byte < 62) {
// `A-Z`
id += (byte - 26).toString(36).toUpperCase()
} else if (byte < 63) {
id += '_'
} else {
} else if (byte > 62) {
id += '-'
} else {
id += '_'
}
}
return id
}
return id
}, '')

module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
2 changes: 1 addition & 1 deletion nanoid.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "nanoid",
"version": "3.3.2",
"description": "A tiny (130 bytes), secure URL-friendly unique string ID generator",
"description": "A tiny (116 bytes), secure URL-friendly unique string ID generator",
"keywords": [
"uuid",
"random",
Expand Down Expand Up @@ -68,7 +68,7 @@
{
"name": "nanoid",
"import": "{ nanoid }",
"limit": "130 B"
"limit": "116 B"
},
{
"name": "customAlphabet",
Expand Down Expand Up @@ -108,7 +108,7 @@
"name": "Brotli all",
"brotli": true,
"import": "{ nanoid, customAlphabet, urlAlphabet }",
"limit": "271 B"
"limit": "260 B"
},
{
"name": "Brotli non-secure",
Expand Down

0 comments on commit f4e7325

Please sign in to comment.