Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions code_to_optimize_js/string_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,26 @@ function longestCommonPrefix(strs) {
* @returns {string} - The title-cased string
*/
function toTitleCase(str) {
return str
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
if (!str) return str;

let result = '';
let capitalizeNext = true;

for (let i = 0, len = str.length; i < len; i++) {
const char = str[i];

if (char === ' ') {
result += char;
capitalizeNext = true;
} else if (capitalizeNext) {
result += char.toUpperCase();
capitalizeNext = false;
} else {
result += char.toLowerCase();
}
}

return result;
}

module.exports = {
Expand Down
Loading