Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reduce bundlesize by moving from while to reduce #355

Merged
merged 2 commits into from Apr 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 8 additions & 13 deletions index.browser.js
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
@@ -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