to title case performance test
by Abdul Ahmad
JavaScript
function toTitleCase({ string }) {
let firstLetter = true;
let finalString = '';
for (var i = 0; i < string.length; i++) {
const letter = string.charAt(i);
if (firstLetter) {
finalString += letter.toUpperCase();
firstLetter = false;
} else {
finalString += letter;
if (letter === ' ') firstLetter = true;
}
}
return finalString;
}
function toTitleCaseMap({ string }) {
const words = string.split(' ');
const titleCasedWords = words.map(word => {
const letters = word.split('');
letters[0] = letters[0].toUpperCase();
return letters.join('');
});
return titleCasedWords.join(' ');
}
let word = '';
for (let i = 0; i < 10000000; i++) {
word += 'a';
if (i % 5 === 0) word += ' ';
}
const startOne = +new Date();
toTitleCase({ string: word });
const endOne = +new Date();
console.log('regular function time: ', endOne - startOne);
const startTwo = +new Date();
toTitleCaseMap({ string: word });
const endTwo = +new Date();
console.log('map function time: ', endTwo - startTwo);