snippetjavascriptMajor
Randomly generate spelling mistake in string
Viewed 0 times
spellingmistakerandomlygeneratestring
Problem
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?
Result from 10 runs:
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 OveerflowSolution
Break it down into one function that randomly repeats a character, and another function which randomly executes that function 50% of the time:
Now you can just call
Note also that the original code has needless multiplication, in that
is equivalent to:
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() > 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() > 0.5is equivalent to:
(Math.random() * 10) >= 5Code Snippets
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() > 0.5 ? repeatRandomChar(str) : str;
}Math.random() > 0.5(Math.random() * 10) >= 5Context
StackExchange Code Review Q#121708, answer score: 22
Revisions (0)
No revisions yet.