Randomly generate spelling mistake in string 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 -&gt; 9 (coin toss)
    if (Math.floor(Math.random() * 10) &gt;= 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
Break it down into one function that randomly repeats a character, and another function which randomly executes that function 50% of the time:

function repeatRandomChar(str) {
  var i = Math.floor(Math.random() * str.length);
  return str.slice(0, i+1) + str.slice(i);
}

function randomTypo(str) {
  return Math.random() &gt; 0.5 ? repeatRandomChar(str) : str;
}


Now you can just call randomTypo('Stack Overflow') 10 times to reproduce your sample data.

Note also that the original code has needless multiplication, in that

 Math.random() &gt; 0.5 


is equivalent to:

 (Math.random() * 10) &gt;= 5