From 6f401c9aaf199cf142eab4744d58a2075cb1f032 Mon Sep 17 00:00:00 2001 From: Fahim Faisaal Date: Thu, 17 Feb 2022 10:30:28 +0600 Subject: [PATCH] pref: optimize the algo by regex ignore the useless traverse in best case by the help of regex and String.prototype.replace method --- String/Lower.js | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/String/Lower.js b/String/Lower.js index 380588994..adf3a361e 100644 --- a/String/Lower.js +++ b/String/Lower.js @@ -1,8 +1,8 @@ /** * @function lower * @description Will convert the entire string to lowercase letters. - * @param {String} url - The input URL string - * @return {String} Lowercase string + * @param {String} str - The input string + * @returns {String} Lowercase string * @example lower("HELLO") => hello * @example lower("He_llo") => he_llo */ @@ -12,17 +12,13 @@ const lower = (str) => { throw new TypeError('Invalid Input Type') } - let lowerString = '' + const lowerString = str.replace(/[A-Z]/g, (_, indexOfUpperChar) => { + const asciiCode = str.charCodeAt(indexOfUpperChar); - for (const char of str) { - let asciiCode = char.charCodeAt(0) - if (asciiCode >= 65 && asciiCode <= 90) { - asciiCode += 32 - } - lowerString += String.fromCharCode(asciiCode) - } + return String.fromCharCode(asciiCode + 32); + }) - return lowerString + return lowerString; } export { lower }