From a4ca11702034e6cc6ba0f03bf831d45697a8811f Mon Sep 17 00:00:00 2001 From: Dorian Niemiec Date: Wed, 28 Aug 2024 10:52:39 +0200 Subject: [PATCH] Optimize fixNodeMojibakeURL function --- src/utils/urlMojibakeFixer.js | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/src/utils/urlMojibakeFixer.js b/src/utils/urlMojibakeFixer.js index f7e6c47..7fd718c 100644 --- a/src/utils/urlMojibakeFixer.js +++ b/src/utils/urlMojibakeFixer.js @@ -1,21 +1,16 @@ // Node.JS mojibake URL fixing function function fixNodeMojibakeURL(string) { - var encoded = ""; - - //Encode URLs - Buffer.from(string, "latin1").forEach((value) => { - if (value > 127) { - encoded += - "%" + (value < 16 ? "0" : "") + value.toString(16).toUpperCase(); - } else { - encoded += String.fromCodePoint(value); - } - }); - - //Upper case the URL encodings - return encoded.replace(/%[0-9a-f-A-F]{2}/g, (match) => { - return match.toUpperCase(); - }); + return Buffer.from(string, "latin1") + .reduce((result, value) => { + if (value > 127) { + result += + "%" + (value < 16 ? "0" : "") + value.toString(16).toUpperCase(); + } else { + result += String.fromCharCode(value); + } + return result; + }, "") + .replace(/%[0-9a-f]{2}/gi, (match) => match.toUpperCase()); } module.exports = fixNodeMojibakeURL;