From f4e7325581e1ab999328adab1e8d8114230751eb Mon Sep 17 00:00:00 2001 From: Arutyunyan Artyom Date: Mon, 18 Apr 2022 13:06:28 +0300 Subject: [PATCH] reduce bundlesize by moving from while to reduce (#355) * reduce bundlesize by moving from while to reduce * reduce bundlesize for brotli by symbols reusing --- index.browser.js | 21 ++++++++------------- nanoid.js | 2 +- package.json | 6 +++--- 3 files changed, 12 insertions(+), 17 deletions(-) diff --git a/index.browser.js b/index.browser.js index 3bffaf7f..7ab1562c 100644 --- a/index.browser.js +++ b/index.browser.js @@ -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 } diff --git a/nanoid.js b/nanoid.js index 5bbc4893..ec242ead 100644 --- a/nanoid.js +++ b/nanoid.js @@ -1 +1 @@ -export let nanoid=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t));for(;t--;){let n=63&r[t];e+=n<36?n.toString(36):n<62?(n-26).toString(36).toUpperCase():n<63?"_":"-"}return e}; \ No newline at end of file +export let nanoid=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce(((t,e)=>t+=(e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e<63?"_":"-"),""); \ No newline at end of file diff --git a/package.json b/package.json index c7e74104..cd0099e1 100644 --- a/package.json +++ b/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", @@ -68,7 +68,7 @@ { "name": "nanoid", "import": "{ nanoid }", - "limit": "130 B" + "limit": "116 B" }, { "name": "customAlphabet", @@ -108,7 +108,7 @@ "name": "Brotli all", "brotli": true, "import": "{ nanoid, customAlphabet, urlAlphabet }", - "limit": "271 B" + "limit": "260 B" }, { "name": "Brotli non-secure",