Task:
There was a study going out a few years ago that said people can read words that are scrambled if the first and last character are left in place. So to help me practice Test Driven Development, I decided program it.
Example:
Correct: “Create attractive offers to reach the right customers”
Scrambled: “Cterae aacrtvitte offres to recah the rghit couemtrss”
For more information about the study visit: Cambridge Word Scramble Study: It’s Fake Already!
Code:
/**
* @author: Larry Battle
* @date: January 2, 2012
* @purpose: Scrambler - to scramble the alphabetical letters in word in such a way to make it still readable and understandable.
* @note: This can be accomplished by have perversing the word order but mixing up every letter in the word except for the first.
*/
var scrambler = {
scrambleStr : function( str ){
if( typeof str !== 'string' ){
return -1;
}
return str.replace( /[^\s]*/g, function( word ){
return word ? scrambler.scrambleWord( word ) : word;
});
},
scrambleWord : function( str ){
if( typeof str !== 'string' ){
return str;
}
str = str.replace( /[a-z]*/ig, function( str2 ){
if( str2 && str2.length > 2 ){
str2 = str2.charAt(0) + scrambler.randomizeStr( str2.substring( 1, str2.length - 1 ) ) + str2.charAt( str2.length - 1 );
}
return str2;
});
return str;
},
randomizeStr : function( str ){
if( typeof str !== 'string' ){
return str;
}
return scrambler.makeArrayRandom( str.split( '' ) ).join( '' );
},
makeArrayRandom : function( arr ){
var j, x, i = arr.length;
while( i ){
j = parseInt(Math.random() * i, 10);
x = arr[--i];
arr[i] = arr[j];
arr[j] = x;
}
return arr;
}
};
Input:
var str = "I can't believe what I'm reading." scrambler.scrambleStr( str );
Output: (Possible outcome)
"I can't beilvee waht I'm rndiaeg."
Try it out for yourself.
Demo: Scrambler
What REALLY is Data Science? Told by a Data Scientist - By Joma Tech
Writing perfect code is a challenging process. That's where code reviews come in to help…
"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"
"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"
My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…