From a584cfda3c80e423f5fce878d8fd9554be0628d1 Mon Sep 17 00:00:00 2001 From: Arutyunyan Artyom Date: Mon, 18 Apr 2022 08:54:50 +0000 Subject: [PATCH] reduce bundlesize by moving from while to reduce --- index.browser.js | 15 +++++---------- nanoid.js | 2 +- package.json | 6 +++--- 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/index.browser.js b/index.browser.js index 3bffaf7f..09368f33 100644 --- a/index.browser.js +++ b/index.browser.js @@ -47,18 +47,14 @@ 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) @@ -70,8 +66,7 @@ let nanoid = (size = 21) => { } 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..f59a441f 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": "264 B" }, { "name": "Brotli non-secure",