My code will generate a spelling mistake inside of a string 50% of the time.
It will retrieve a letter from a random index in the string like, "t" and then duplicate that letter like, "tt" and store it in the spelling mistake variable.
It will then replace, "t" with "tt" in the string to replicate a spelling mistake. (50% of the time.)
How can I improve my code to make it complete the same task, but with less lines of code and using the least amount of resources possible?
(function() {
function replaceStr(str, pos, value) {
var arr = str.split('');
arr[pos] = value;
return arr.join('');
}
var myString = "Stack Overflow";
var letterIndex = Math.floor(Math.random() * myString.length); // Example: 1
var letter = myString.charAt(letterIndex); // Example: "t"
var mistake = letter + letter; // Example: "tt"
// 0 -> 9 (coin toss)
if (Math.floor(Math.random() * 10) >= 5) {
return replaceStr(myString, letterIndex, mistake);
} else {
return myString;
}
})();
Result from 10 runs:
Stack Overflow
Stackk Overflow
Stack Overflow
Sttack Overflow
Stack Overflow
Stack Oveerflow
Stack Overrflow
Stack Overfllow
Stack Overflow
Stack Oveerflow