Skip to content
Closed
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
39 changes: 22 additions & 17 deletions code_to_optimize_js/string_utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,8 @@
* @returns {string} - The reversed string
*/
function reverseString(str) {
// Intentionally inefficient O(n²) implementation for testing
let result = '';
for (let i = str.length - 1; i >= 0; i--) {
// Rebuild the entire result string each iteration (very inefficient)
let temp = '';
for (let j = 0; j < result.length; j++) {
temp += result[j];
}
temp += str[i];
result = temp;
}
return result;
// Optimized O(n) implementation using array operations
return str.split('').reverse().join('');
}

/**
Expand Down Expand Up @@ -79,11 +69,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