Skip to content

Commit

Permalink
Much faster implementation (#466)
Browse files Browse the repository at this point in the history
* Update nanoid.js

Much faster now

* Update index.browser.js

* fix eslint errors and revert nanoid.js changes

* Use optimized alphabet and update size limit
  • Loading branch information
samuelgozi authored Feb 1, 2024
1 parent dfcfcc6 commit 70409a3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 24 deletions.
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

0 comments on commit 70409a3

Please sign in to comment.