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

Much faster implementation #466

Merged
merged 4 commits into from
Feb 1, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 10 additions & 23 deletions index.browser.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// This file replaces `index.js` in bundlers like webpack or Rollup,
// according to `browser` config in `package.json`.

import { urlAlphabet } from './url-alphabet/index.js';
export { urlAlphabet } from './url-alphabet/index.js'

export let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
Expand Down Expand Up @@ -47,25 +47,12 @@ export let customRandom = (alphabet, defaultSize, getRandom) => {
export let customAlphabet = (alphabet, size = 21) =>
customRandom(alphabet, size, random)

export 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.
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 > 62) {
id += '-'
} else {
id += '_'
}
return id
}, '')

export let nanoid = (len = 21) => {
let id = "";
let rand = crypto.getRandomValues(new Uint8Array(len));
// Using the bitwise AND operator to "cap" the value of
// the random byte from 255 to 63, in that way we can make sure
// that the value will be a valid index for the "chars" string.
for (let i = 0; i < len; i++) id += urlAlphabet[rand[i] & 63];
return id;
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
{
"name": "nanoid",
"import": "{ nanoid }",
"limit": "109 B"
"limit": "124 B"
},
{
"name": "customAlphabet",
Expand Down
Loading