mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2026-03-13 15:21:15 +08:00
pref: optimize the algo by regex
ignore the useless traverse in best case by the help of regex and String.prototype.replace method
This commit is contained in:
@@ -1,8 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* @function lower
|
* @function lower
|
||||||
* @description Will convert the entire string to lowercase letters.
|
* @description Will convert the entire string to lowercase letters.
|
||||||
* @param {String} url - The input URL string
|
* @param {String} str - The input string
|
||||||
* @return {String} Lowercase string
|
* @returns {String} Lowercase string
|
||||||
* @example lower("HELLO") => hello
|
* @example lower("HELLO") => hello
|
||||||
* @example lower("He_llo") => he_llo
|
* @example lower("He_llo") => he_llo
|
||||||
*/
|
*/
|
||||||
@@ -12,17 +12,13 @@ const lower = (str) => {
|
|||||||
throw new TypeError('Invalid Input Type')
|
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) {
|
return String.fromCharCode(asciiCode + 32);
|
||||||
let asciiCode = char.charCodeAt(0)
|
})
|
||||||
if (asciiCode >= 65 && asciiCode <= 90) {
|
|
||||||
asciiCode += 32
|
|
||||||
}
|
|
||||||
lowerString += String.fromCharCode(asciiCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return lowerString
|
return lowerString;
|
||||||
}
|
}
|
||||||
|
|
||||||
export { lower }
|
export { lower }
|
||||||
|
|||||||
Reference in New Issue
Block a user