X Tutup
Skip to content

Commit 6f401c9

Browse files
committed
pref: optimize the algo by regex
ignore the useless traverse in best case by the help of regex and String.prototype.replace method
1 parent a2822e1 commit 6f401c9

File tree

1 file changed

+7
-11
lines changed

1 file changed

+7
-11
lines changed

String/Lower.js

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/**
22
* @function lower
33
* @description Will convert the entire string to lowercase letters.
4-
* @param {String} url - The input URL string
5-
* @return {String} Lowercase string
4+
* @param {String} str - The input string
5+
* @returns {String} Lowercase string
66
* @example lower("HELLO") => hello
77
* @example lower("He_llo") => he_llo
88
*/
@@ -12,17 +12,13 @@ const lower = (str) => {
1212
throw new TypeError('Invalid Input Type')
1313
}
1414

15-
let lowerString = ''
15+
const lowerString = str.replace(/[A-Z]/g, (_, indexOfUpperChar) => {
16+
const asciiCode = str.charCodeAt(indexOfUpperChar);
1617

17-
for (const char of str) {
18-
let asciiCode = char.charCodeAt(0)
19-
if (asciiCode >= 65 && asciiCode <= 90) {
20-
asciiCode += 32
21-
}
22-
lowerString += String.fromCharCode(asciiCode)
23-
}
18+
return String.fromCharCode(asciiCode + 32);
19+
})
2420

25-
return lowerString
21+
return lowerString;
2622
}
2723

2824
export { lower }

0 commit comments

Comments
 (0)
X Tutup