Skip to content

Commit 41967d8

Browse files
authored
Update nanoid and export it (#481)
* Update nanoid and export it Nanoid recently put out 3.0, which rewrote a bunch of their implementation, and 3.0.2 made further tweaks to the non-secure ID function. Since we've inlined this, we might as well swipe their updates, and export it ourselves if anyone wants to use it. * Add nanoid to API exports
1 parent ce0aeae commit 41967d8

File tree

3 files changed

+20
-22
lines changed

3 files changed

+20
-22
lines changed

etc/redux-toolkit.api.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,9 @@ export function isImmutableDefault(value: unknown): boolean;
291291
// @public
292292
export function isPlain(val: any): boolean;
293293

294+
// @public (undocumented)
295+
export let nanoid: (size?: number) => string;
296+
294297
export { OutputParametricSelector }
295298

296299
export { OutputSelector }

src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,3 +100,5 @@ export {
100100
unwrapResult,
101101
SerializedError
102102
} from './createAsyncThunk'
103+
104+
export { nanoid } from './nanoid'

src/nanoid.ts

Lines changed: 15 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,20 @@
1-
// Borrowed from https://github.com/ai/nanoid/tree/master/non-secure
2-
// This alphabet uses a-z A-Z 0-9 _- symbols.
3-
// Symbols are generated for smaller size.
4-
// -_zyxwvutsrqponmlkjihgfedcba9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA
5-
let url = '-_'
6-
// Loop from 36 to 0 (from z to a and 9 to 0 in Base36).
7-
let i = 36
8-
while (i--) {
9-
// 36 is radix. Number.prototype.toString(36) returns number
10-
// in Base36 representation. Base36 is like hex, but it uses 0–9 and a-z.
11-
url += i.toString(36)
12-
}
13-
// Loop from 36 to 10 (from Z to A in Base36).
14-
i = 36
15-
while (i-- - 10) {
16-
url += i.toString(36).toUpperCase()
17-
}
1+
// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js
2+
// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped
3+
// optimize the gzip compression for this alphabet.
4+
let urlAlphabet =
5+
'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'
186

19-
export function nanoid(size = 21) {
7+
/**
8+
*
9+
* @public
10+
*/
11+
export let nanoid = (size = 21) => {
2012
let id = ''
21-
// Compact alternative for `for (var i = 0; i < size; i++)`
22-
while (size--) {
23-
// `| 0` is compact and faster alternative for `Math.floor()`
24-
id += url[(Math.random() * 64) | 0]
13+
// A compact alternative for `for (var i = 0; i < step; i++)`.
14+
let i = size
15+
while (i--) {
16+
// `| 0` is more compact and faster than `Math.floor()`.
17+
id += urlAlphabet[(Math.random() * 64) | 0]
2518
}
2619
return id
2720
}

0 commit comments

Comments
 (0)