Change API for custom alphabet and random
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Andrey Sitnik · committed by Andrey Sitnik · parent b488b48 · Browse files · 15 files·+174 added−157 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+174 added−157 removed
- tests:+38 added−30 removed
- other:+136 added−127 removed
Provenance
- Commit
65b308b- Tree
0ffbc70- Author
Andrey Sitnik <andrey@sitnik.ru>- Committer
Andrey Sitnik <andrey@sitnik.ru>- Parent
b488b48
15 files changed+174 added−157 removed
modified:async/index.browser.js+18 added-16 removed
1123452 unmodified lines8910111213141213141516171819202122232324252526272829303132333426272829303132333435363738394022 unmodified lines636465666567let nanoid2 = (size, alphabet) => {let customAlphabet = (alphabet, size) => { // We can’t use bytes bigger than the alphabet. To make bytes values closer // to the alphabet, we apply bitmask on them. We look for the closest // `2 ** x - 1` number, which will be bigger than alphabet size. If we have // 30 symbols in the alphabet, we will take 31 (00011111).2 unmodified lines // Bitmask is not a perfect solution (in our example it will pass 31 bytes, // which is bigger than the alphabet). As a result, we will need more bytes, // than ID size, because we will refuse bytes bigger than the alphabet.
// Every hardware random generator call is costly, // because we need to wait for entropy collection. This is why often it will // be faster to ask for few extra bytes in advance, to avoid additional calls. // Every hardware random generator call is costly, because we need to wait // for entropy collection. This is why often it will be faster to ask for // few extra bytes in advance, to avoid additional calls.
// Here we calculate how many random bytes should we call in advance. // It depends on ID length, mask / alphabet size and magic number 1.6 // (which was selected according benchmarks).
// -~f => Math.ceil(f) if n is float number // -~i => i + 1 if n is integer number let step = -~(1.6 * mask * size / alphabet.length) let id = ''
return () => { let id = '' while (true) { let bytes = self.crypto.getRandomValues(new Uint8Array(step)) // Compact alternative for `for (var j = 0; j < step; j++)` let i = step while (i--) { // If random byte is bigger than alphabet even after bitmask, // we refuse it by `|| ''`. id += alphabet[bytes[i] & mask] || '' // More compact than `id.length + 1 === size` if (id.length === +size) return id while (true) { let bytes = self.crypto.getRandomValues(new Uint8Array(step)) // Compact alternative for `for (var j = 0; j < step; j++)` let i = step while (i--) { // If random byte is bigger than alphabet even after bitmask, // we refuse it by `|| ''`. id += alphabet[bytes[i] & mask] || '' // More compact than `id.length + 1 === size` if (id.length === +size) return id } } }}
22 unmodified lines } return Promise.resolve(id)}
module.exports = { nanoid, nanoid2 }module.exports = { nanoid, customAlphabet }modified:async/index.d.ts+7 added-3 removed
26 unmodified lines2728293031323132333435363737383940414243444546474849505 unmodified lines26 unmodified lines * @param alphabet Symbols to be used in ID. * @return Promise with random string. * * ```js * const { nanoid2 } = require('nanoid/async') * generate(5, '0123456789абвгдеё').then(id => { * import { customAlphabet } from 'nanoid/async' * const nanoid = customAlphabet('0123456789абвгдеё', 5) * nanoid().then(id => { * model.id = id //=> "8ё56а" * }) * ``` */export function nanoid2 (size: number, alphabet: string): Promise<string>export function customAlphabet ( alphabet: string, size: number): () => Promise<string>
/** * Return array with random bytes from hardware random generator. * * ```js * import { random } from 'nanoid/async' * random(5).then(bytes => { * bytes //=> [10, 67, 212, 67, 89] * }) * ```5 unmodified linesmodified:async/index.js+6 added-6 removed
14 unmodified lines1516171819192021222324252627282930312930313233343511 unmodified lines474849505151525354557 unmodified lines63646566676714 unmodified lines } })})
let nanoid2 = (size, alphabet) => {let customAlphabet = (alphabet, size) => { // We can’t use bytes bigger than the alphabet. To make bytes values closer // to the alphabet, we apply bitmask on them. We look for the closest // `2 ** x - 1` number, which will be bigger than alphabet size. If we have // 30 symbols in the alphabet, we will take 31 (00011111). let mask = (2 << 31 - Math.clz32((alphabet.length - 1) | 1)) - 1 // Bitmask is not a perfect solution (in our example it will pass 31 bytes, // which is bigger than the alphabet). As a result, we will need more bytes, // than ID size, because we will refuse bytes bigger than the alphabet.
// Every hardware random generator call is costly, // because we need to wait for entropy collection. This is why often it will // be faster to ask for few extra bytes in advance, to avoid additional calls. // Every hardware random generator call is costly, because we need to wait // for entropy collection. This is why often it will be faster to ask for // few extra bytes in advance, to avoid additional calls.
// Here we calculate how many random bytes should we call in advance. // It depends on ID length, mask / alphabet size and magic number 1.6 // (which was selected according benchmarks).11 unmodified lines } return tick(id) })
return tick('') return () => tick('')}
let nanoid = (size = 21) => random(size).then(bytes => { let id = ''7 unmodified lines } return id})
module.exports = { nanoid, nanoid2 }module.exports = { nanoid, customAlphabet }modified:non-secure/index.d.ts+4 added-3 removed
19 unmodified lines20 * @param alphabet Symbols to be used in ID.21 * @returns Random string.22 *23 * ```js24- * const { nanoid2 } = require('nanoid/non-secure')25- * model.id = generate(5, '0123456789абвгдеё') //=> "8ё56а"24+ * import { customAlphabet } from 'nanoid/non-secure'25+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)26+ * model.id = //=> "8ё56а"27 * ```28 */28-export function nanoid2 (size: number, alphabet: string): string29+export function customAlphabet (alphabet: string, size: number): () => stringmodified:non-secure/index.js+17 added-22 removed
1-let nanoid2 = (size, alphabet) => {2- let id = ''3- // Complete alternative for `for (var i = 0; i < size; i++)`4- while (size--) {5- // `| 0` is compact and faster alternative for `Math.floor()`6- id += alphabet[Math.random() * alphabet.length | 0]1+let { urlAlphabet } = require('..')2+3+let customAlphabet = (alphabet, size) => {4+ return () => {5+ let id = ''6+ // Complete alternative for `for (var i = 0; i < size; i++)`7+ let i = size8+ while (i--) {9+ // `| 0` is compact and faster alternative for `Math.floor()`10+ id += alphabet[Math.random() * alphabet.length | 0]11+ }12+ return id13 }8- return id14 }15 16 let nanoid = (size = 21) => {17 let id = ''13- // Compact alternative for `for (var i = 0; i < size; i++)`14- while (size--) {18+ // Complete alternative for `for (var i = 0; i < size; i++)`19+ let i = size20+ while (i--) {21 // `| 0` is compact and faster alternative for `Math.floor()`16- let byte = Math.random() * 64 | 017- if (byte < 36) {18- // 0-9a-z19- id += byte.toString(36)20- } else if (byte < 62) {21- // A-Z22- id += (byte - 26).toString(36).toUpperCase()23- } else if (byte < 63) {24- id += '_'25- } else {26- id += '-'27- }22+ id += urlAlphabet[Math.random() * 64 | 0]23 }24 return id25 }26 32-module.exports = { nanoid, nanoid2 }27+module.exports = { nanoid, customAlphabet }modified:test/demo/index.js+4 added-2 removed
1 unmodified line2 import { v4 as uuid4 } from 'uuid'3 import rndm from 'rndm'4 import uid from 'uid-safe'5 6-import { nanoid, nanoid2, random } from '../../'6+import { nanoid, customAlphabet, random } from '../../'7 import { nanoid as nonSecure } from '../../non-secure'8 9 const COUNT = 50 * 100010 const ALPHABET = 'abcdefghijklmnopqrstuvwxyz'11 const LENGTH = ALPHABET.length12 13+let nanoid2 = customAlphabet(ALPHABET, LENGTH)14+15 function print (number) {16 return String(Math.floor(number * 100))17 .replace(/\d{6}$/, ',$&')18 .replace(/\d{3}$/, ',$&')52 unmodified lines71 }72 return result73 }),74 () => printDistr('nanoid', () => nanoid()),73- () => printDistr('nanoid2', () => nanoid2(ALPHABET, LENGTH)),75+ () => printDistr('nanoid2', () => nanoid2()),76 () => printDistr('uid.sync', () => uid.sync(21)),77 () => printDistr('uuid/v4', () => uuid4()),78 () => printDistr('shortid', () => shortid()),79 () => printDistr('rndm', () => rndm()),20 unmodified linesmodified:test/async.test.js+6 added-4 removed
24 unmodified lines25 }26 27 for (let type of ['node', 'browser']) {28 describe(`${ type }`, () => {29- let { nanoid, nanoid2 } = type === 'node' ? node : browser29+ let { nanoid, customAlphabet } = type === 'node' ? node : browser30 31 describe('nanoid', () => {32 function mock (callback) {33 crypto.randomFill = callback71 unmodified lines105 })106 }107 })108 109- describe('nanoid2', () => {109+ describe('customAlphabet', () => {110 it('has options', async () => {111+ let nanoidA = customAlphabet('a', 5)111- let id = await nanoid2(5, 'a')112+ let id = await nanoidA()113 expect(id).toEqual('aaaaa')114 })115 116 it('has flat distribution', async () => {117 let COUNT = 100 * 1000118 let LENGTH = 5119 let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'120+ let nanoid2 = customAlphabet(ALPHABET, LENGTH)121 122 let chars = { }123 await Promise.all(times(100, async () => {122- let id = await nanoid2(LENGTH, ALPHABET)124+ let id = await nanoid2()125 expect(id).toHaveLength(LENGTH)126 for (let char of id) {127 if (!chars[char]) chars[char] = 0128 chars[char] += 115 unmodified linesmodified:test/benchmark+10 added-7 removed
6 unmodified lines7 let rndm = require('rndm')8 let srs = require('secure-random-string')9 let uid = require('uid-safe')10 11-let { nanoid: asyncNanoid, nanoid2: asyncNanoid2 } = require('../async')11+let { nanoid: aNanoid, customAlphabet: aCustomAlphabet } = require('../async')12+let { nanoid, customAlphabet } = require('../')13 let { nanoid: nonSecure } = require('../non-secure')13-let { nanoid, nanoid2 } = require('../')14 15 let suite = new benchmark.Suite()16 17+let nanoid2 = customAlphabet('1234567890abcdef-', 10)18+let asyncNanoid2 = aCustomAlphabet('1234567890abcdef-', 10)19+20 function formatNumber (number) {21 return String(number)22 .replace(/\d{3}$/, ',$&')23 .replace(/^(\d)(\d{3})/, '$1,$2')2 unmodified lines26 suite27 .add('nanoid', () => {28 nanoid()29 })27- .add('nanoid2', () => {28- nanoid2(10, '1234567890abcdef-')30+ .add('customAlphabet', () => {31+ nanoid2()32 })33 .add('uid.sync', () => {34 uid.sync(14)35 })8 unmodified lines44 })45 .add('async nanoid', {46 defer: true,47 fn (defer) {45- asyncNanoid().then(() => {48+ aNanoid().then(() => {49 defer.resolve()50 })51 }52 })50- .add('async nanoid2', {53+ .add('async customAlphabet', {54 defer: true,55 fn (defer) {53- asyncNanoid2(10, '1234567890abcdef-').then(() => {56+ asyncNanoid2().then(() => {57 defer.resolve()58 })59 }60 })33 unmodified linesmodified:test/index.test.js+12 added-13 removed
12 unmodified lines13 let node = require('../index.js')14 15 for (let type of ['node', 'browser']) {16 describe(`${ type }`, () => {17- let { nanoid, nanoid2, nanoid3, random, urlAlphabet } =17+ let { nanoid, customAlphabet, customRandom, random, urlAlphabet } =18 type === 'node' ? node : browser19 20 describe('nanoid', () => {21 it('generates URL-friendly IDs', () => {49 unmodified lines71 expect(max - min).toBeLessThanOrEqual(0.05)72 })73 })74 75- describe('nanoid2', () => {75+ describe('customAlphabet', () => {76 it('has options', () => {77+ let nanoidA = customAlphabet('a', 5)77- expect(nanoid2(5, 'a')).toEqual('aaaaa')78+ expect(nanoidA()).toEqual('aaaaa')79 })80 81 it('has flat distribution', () => {82 let COUNT = 100 * 100083 let LENGTH = 584 let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'85+ let nanoid2 = customAlphabet(ALPHABET, LENGTH)86 87 let chars = { }88 for (let i = 0; i < COUNT; i++) {87- let id = nanoid2(LENGTH, ALPHABET)89+ let id = nanoid2()90 for (let char of id) {91 if (!chars[char]) chars[char] = 092 chars[char] += 193 }11 unmodified lines105 expect(max - min).toBeLessThanOrEqual(0.05)106 })107 })108 107- describe('nanoid3', () => {109+ describe('customRandom', () => {110 it('supports generator', () => {111 let sequence = [2, 255, 3, 7, 7, 7, 7, 7, 0, 1]110- function customRandom (size) {112+ function fakeRandom (size) {113 let bytes = []114 for (let i = 0; i < size; i += sequence.length) {115 bytes = bytes.concat(sequence.slice(0, size - i))116 }117 return bytes118 }119+ let nanoid4 = customRandom('abcde', 4, fakeRandom)120+ let nanoid18 = customRandom('abcde', 18, fakeRandom)117- expect(nanoid3(4, 'abcde', customRandom)).toEqual('adca')118- expect(nanoid3(18, 'abcde', customRandom)).toEqual('cbadcbadcbadcbadcc')121+ expect(nanoid4()).toEqual('adca')122+ expect(nanoid18()).toEqual('cbadcbadcbadcbadcc')123 })120-121- it('respects size', () => {122- expect(nanoid3(4, 'abcde', random)).toHaveLength(4)123- expect(nanoid3(20, 'abcde', random)).toHaveLength(20)124- })124 })125 126 describe('urlAlphabet', () => {127 it('is string', () => {30 unmodified linesmodified:test/non-secure.test.js+6 added-4 removed
1-let { nanoid, nanoid2 } = require('../non-secure')1+let { nanoid, customAlphabet } = require('../non-secure')2 3 let { urlAlphabet } = require('..')4 5 describe('nanoid', () => {49 unmodified lines55 expect(max - min).toBeLessThanOrEqual(0.05)56 })57 })58 59-describe('nanoid2', () => {59+describe('customAlphabet', () => {60 it('has options', () => {61+ let nanoidA = customAlphabet('a', 5)61- expect(nanoid2(5, 'a')).toEqual('aaaaa')62+ expect(nanoidA()).toEqual('aaaaa')63 })64 65 it('has flat distribution', () => {66 let COUNT = 100 * 100067 let LENGTH = 568 let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'69+ let nanoid2 = customAlphabet(ALPHABET, LENGTH)70 71 let chars = { }72 for (let i = 0; i < COUNT; i++) {71- let id = nanoid2(LENGTH, ALPHABET)73+ let id = nanoid2()74 for (let char of id) {75 if (!chars[char]) chars[char] = 076 chars[char] += 177 }14 unmodified linesmodified:index.browser.js+19 added-17 removed
49 unmodified lines50 // }51 52 let random = bytes => self.crypto.getRandomValues(new Uint8Array(bytes))53 54-let nanoid3 = (size, alphabet, getRandom) => {54+let customRandom = (alphabet, size, getRandom) => {55 // We can’t use bytes bigger than the alphabet. To make bytes values closer56 // to the alphabet, we apply bitmask on them. We look for the closest57 // `2 ** x - 1` number, which will be bigger than alphabet size. If we have58 // 30 symbols in the alphabet, we will take 31 (00011111).2 unmodified lines61 // Bitmask is not a perfect solution (in our example it will pass 31 bytes,62 // which is bigger than the alphabet). As a result, we will need more bytes,63 // than ID size, because we will refuse bytes bigger than the alphabet.64 65- // Every hardware random generator call is costly,66- // because we need to wait for entropy collection. This is why often it will67- // be faster to ask for few extra bytes in advance, to avoid additional calls.65+ // Every hardware random generator call is costly, because we need to wait66+ // for entropy collection. This is why often it will be faster to ask for67+ // few extra bytes in advance, to avoid additional calls.68 69 // Here we calculate how many random bytes should we call in advance.70 // It depends on ID length, mask / alphabet size and magic number 1.671 // (which was selected according benchmarks).72 73 // -~f => Math.ceil(f) if n is float number74 // -~i => i + 1 if n is integer number75 let step = -~(1.6 * mask * size / alphabet.length)76- let id = ''76 77+ return () => {78+ let id = ''78- while (true) {79- let bytes = getRandom(step)80- // Compact alternative for `for (var j = 0; j < step; j++)`81- let j = step82- while (j--) {83- // If random byte is bigger than alphabet even after bitmask,84- // we refuse it by `|| ''`.85- id += alphabet[bytes[j] & mask] || ''86- // More compact than `id.length + 1 === size`87- if (id.length === +size) return id79+ while (true) {80+ let bytes = getRandom(step)81+ // Compact alternative for `for (var j = 0; j < step; j++)`82+ let j = step83+ while (j--) {84+ // If random byte is bigger than alphabet even after bitmask,85+ // we refuse it by `|| ''`.86+ id += alphabet[bytes[j] & mask] || ''87+ // More compact than `id.length + 1 === size`88+ if (id.length === +size) return id89+ }90 }91 }92 }93 92-let nanoid2 = (size, alphabet) => nanoid3(size, alphabet, random)94+let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)95 96 let nanoid = (size = 21) => {97 let id = ''98 let bytes = self.crypto.getRandomValues(new Uint8Array(size))20 unmodified lines119 }120 return id121 }122 121-module.exports = { nanoid, nanoid2, nanoid3, urlAlphabet, random }123+module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }modified:index.d.ts+19 added-15 removed
20 unmodified lines21 * will not be secure.22 *23 * @param alphabet Symbols to be used in ID.24 * @param size The number of symbols in ID. Defauls is 21.25- * @returns Random string.25+ * @returns Random string generator26 *27 * ```js28- * const { nanoid2 } = require('nanoid')29- * model.id = nanoid2(5, '0123456789абвгдеё') //=> "8ё56а"28+ * const { customAlphabet } = require('nanoid')29+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)30+ * nanoid() //=> "8ё56а"31 * ```32 */32-export function nanoid2 (size: number, alphabet: string): string33+export function customAlphabet (alphabet: string, size: number): () => string34 35 /**36 * Generate unique ID with custom random generator and alphabet.37 *38 * Alphabet must contain 256 symbols or less. Otherwise, the generator39 * will not be secure.40 *41 * ```js41- * import { nanoid3 } from 'nanoid/format'42+ * import { customRandom } from 'nanoid/format'43 *43- * nanoid3(5, "abcdef", size => {44+ * const nanoid = customRandom("abcdef", 5, size => {45 * const random = []46 * for (let i = 0; i < size; i++) {47 * random.push(randomByte())48 * }49 * return random49- * }) //=> "fbaef"50+ * })51+ *52+ * nanoid() //=> "fbaef"53 * ```54 *52- * @param size The number of symbols in new random string.55 * @param alphabet Symbols to be used in new random string.56+ * @param size The number of symbols in new random string.57 * @param random The random bytes generator.55- * @returns Random string.58+ * @returns Random string generator59 */57-export function nanoid3 (58- size: number,60+export function customRandom (61 alphabet: string,62+ size: number,63 random: (bytes: number) => Uint8Array,61-): string64+): () => string65 66 /**67 * URL safe symbols.68 *69 * ```js70 * import { urlAlphabet } from 'nanoid'71+ * const nanoid = customRandom(urlAlphabet, 10)68- * generate(10, url) //=> "Uakgb_J5m9"72+ * nanoid() //=> "Uakgb_J5m9"73 * ```74 */75 export const urlAlphabet: string76 77 /**78 * Return array with random bytes from hardware random generator.79 *80 * ```js77- * import { nanoid3, random } from 'nanoid'78- * nanoid3(5, "abcdef", random) //=> "fbaef"81+ * import { customRandom, random } from 'nanoid'82+ * const nanoid = customRandom("abcdef", 5, random)83 * ```84 *85 * @param bytes The size of array.86 * @returns Arrays with random bytes.2 unmodified linesmodified:index.js+19 added-17 removed
15 unmodified lines16 }17 return crypto.randomFillSync(buffer)18 }19 20-let nanoid3 = (size, alphabet, getRandom) => {20+let customRandom = (alphabet, size, getRandom) => {21 // We can’t use bytes bigger than the alphabet. To make bytes values closer22 // to the alphabet, we apply bitmask on them. We look for the closest23 // `2 ** x - 1` number, which will be bigger than alphabet size. If we have24 // 30 symbols in the alphabet, we will take 31 (00011111).1 unmodified line26 // Bitmask is not a perfect solution (in our example it will pass 31 bytes,27 // which is bigger than the alphabet). As a result, we will need more bytes,28 // than ID size, because we will refuse bytes bigger than the alphabet.29 30- // Every hardware random generator call is costly,31- // because we need to wait for entropy collection. This is why often it will32- // be faster to ask for few extra bytes in advance, to avoid additional calls.30+ // Every hardware random generator call is costly, because we need to wait31+ // for entropy collection. This is why often it will be faster to ask for32+ // few extra bytes in advance, to avoid additional calls.33 34 // Here we calculate how many random bytes should we call in advance.35 // It depends on ID length, mask / alphabet size and magic number 1.636 // (which was selected according benchmarks).37 let step = Math.ceil(1.6 * mask * size / alphabet.length)38- let id = ''38 39+ return () => {40+ let id = ''40- while (true) {41- let bytes = getRandom(step)42- // Compact alternative for `for (var i = 0; i < step; i++)`43- let i = step44- while (i--) {45- // If random byte is bigger than alphabet even after bitmask,46- // we refuse it by `|| ''`.47- id += alphabet[bytes[i] & mask] || ''48- // More compact than `id.length + 1 === size`49- if (id.length === +size) return id41+ while (true) {42+ let bytes = getRandom(step)43+ // Compact alternative for `for (var i = 0; i < step; i++)`44+ let i = step45+ while (i--) {46+ // If random byte is bigger than alphabet even after bitmask,47+ // we refuse it by `|| ''`.48+ id += alphabet[bytes[i] & mask] || ''49+ // More compact than `id.length + 1 === size`50+ if (id.length === +size) return id51+ }52 }53 }54 }55 54-let nanoid2 = (size, alphabet) => nanoid3(size, alphabet, random)56+let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)57 58 let nanoid = (size = 21) => {59 let bytes = random(size)60 let id = ''7 unmodified lines68 }69 return id70 }71 70-module.exports = { nanoid, nanoid2, nanoid3, urlAlphabet, random }72+module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }modified:package.json+9 added-9 removed
65 unmodified lines66 "import": "{ nanoid }",67 "limit": "110 B"68 },69 {70- "name": "nanoid2",71- "import": "{ nanoid2 }",70+ "name": "customAlphabet",71+ "import": "{ customAlphabet }",72 "limit": "144 B"73 },74 {75 "name": "urlAlphabet",3 unmodified lines79 {80 "name": "non-secure nanoid",81 "import": "{ nanoid }",82 "path": "non-secure/index.js",83- "limit": "85 B"83+ "limit": "103 B"84 },85 {86- "name": "non-secure nanoid2",87- "import": "{ nanoid2 }",86+ "name": "non-secure customAlphabet",87+ "import": "{ customAlphabet }",88 "path": "non-secure/index.js",89- "limit": "44 B"89+ "limit": "45 B"90 },91 {92 "name": "async nanoid",93 "import": "{ nanoid }",94 "path": "async/index.js",95 "limit": "120 B"96 },97 {98- "name": "async nanoid2",99- "import": "{ nanoid2 }",98+ "name": "async customAlphabet",99+ "import": "{ customAlphabet }",100 "path": "async/index.js",101- "limit": "130 B"101+ "limit": "132 B"102 }103 ],104 "eslintConfig": {105 "extends": "@logux/eslint-config",75 unmodified linesmodified:README.md+18 added-19 removed
322 unmodified lines323 324 325 ### Custom Alphabet or Length326 327-`nanoid2` allows you to change ID’s alphabet. It has `2` in the name,328-because it accepts 2 arguments (alphabet and optional size) in contrast329-to `nanoid`, which accepts only 1 argument (optional size).327+`customAlphabet` allows you to create `nanoid` with own alphabet and ID length.328 329 ```js332-import { nanoid2 } from 'nanoid'333-model.id = nanoid2(10, '1234567890abcdef') //=> "4f90d13a42"330+import { customAlphabet } from 'nanoid'331+const nanoid = customAlphabet('1234567890abcdef', 10)332+model.id = nanoid() //=> "4f90d13a42"333 ```334 335 Check the safety of your custom alphabet and ID length336 in our [ID collision probability] calculator.4 unmodified lines341 342 Asynchronous and non-secure API is also available:343 344 ```js346-import { nanoid2 } from 'nanoid/async'345+import { customAlphabet } from 'nanoid/async'346+const nanoid = customAlphabet('1234567890abcdef', 10)347 async function createUser () {348- user.id = await nanoid2(10, '1234567890abcdef')348+ user.id = await nanoid()349 }350 ```351 352 ```js353-import { nanoid2 } from 'nanoid/non-secure'354-user.id = nanoid2(10, '1234567890abcdef')353+import { customAlphabet } from 'nanoid/non-secure'354+const nanoid = customAlphabet('1234567890abcdef', 10)355+user.id = nanoid()356 ```357 358 [ID collision probability]: https://alex7kom.github.io/nano-nanoid-cc/359 [`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary360 361 362 ### Custom Random Bytes Generator363 363-You can replace the default safe random generator using the `nanoid3` module.364-For instance, to use a seed-based generator.364+`customRandom` allows you to create `nanoid` and replace the default365+safe random generator. For instance, to use a seed-based generator.366 366-This function has `3` in the name, because it accepts 3 arguments367-(generator, alphabet and size).368-367 ```js370-import { nanoid3 } from 'nanoid`368+import { customRandom } from 'nanoid`369 370 function random (size) {371 const result = []372 for (let i = 0; i < size; i++) {1 unmodified line374 }375 return result376 }377 378+const nanoid = customRandom('abcdef', 10, random)380-nanoid3(10, 'abcdef', random) //=> "fbaefaadeb"379+nanoid() //=> "fbaefaadeb"380 ```381 382 `random` callback must accept the array size and return an array383 with random numbers.1 unmodified line385 If you want to use the same URL-friendly symbols with `nanoid3`,386 you can get the default alphabet from the `urlAlphabet`.387 388 ```js390-const { nanoid3, urlAlphabet } = require('nanoid')391-nanoid3(10, urlAlphabet, random) //=> "93ce_Ltuub"389+const { customRandom, urlAlphabet } = require('nanoid')390+const nanoid = customRandom(urlAlphabet, 10, random)391 ```392 394-Asynchronous and non-secure APIs are not available for `nanoid3`.393+Asynchronous and non-secure APIs are not available for `customRandom`.