Last active
August 29, 2015 14:15
-
-
Save mikeperri/629a38927ece80cdff9e to your computer and use it in GitHub Desktop.
Naturally distort text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
If a character is distorted, it will be replaced with an adjacent key on the keyboard. | |
The probability that a character will be distorted is determined by the function. | |
HOW TO USE: | |
Open a new tab and type about:blank in the address bar, press enter | |
Right click and choose 'Inspect Element' | |
Choose the 'Console' tab | |
Paste all of this in and press enter | |
*/ | |
var kybdMatrix = ['qwertyuiop','asdfghjkl;','zxcvbnm,./']; | |
//(p*100) percent chance of distorting character c | |
function distortChar(c, p){ | |
var r = Math.random(); | |
if(r <= p){ | |
//Distort this character | |
//Find character in keyboard matrix | |
for(var kybdRow = 0; kybdRow < kybdMatrix.length; kybdRow++){ | |
var kybdCol = kybdMatrix[kybdRow].indexOf(c); | |
if(kybdCol > -1){ | |
//kybdRow and kybdCol are correct | |
var r2 = Math.random(); | |
var r3 = Math.random(); | |
if(r2 > .5){ | |
//Down or up | |
if(kybdRow == 0 || (r3 > .5 && kybdRow != kybdMatrix.length-1)){ | |
//Down | |
kybdRow++; | |
} else { | |
//Up | |
kybdRow--; | |
} | |
} else { | |
//Right oar left | |
if(kybdCol == 0 || (r3 > .5 && kybdCol != kybdMatrix[0].length-1)){ | |
//Right | |
kybdCol++; | |
} else { | |
//Left | |
kybdCol--; | |
} | |
} | |
return kybdMatrix[kybdRow][kybdCol]; | |
} | |
} | |
return c; | |
} else { | |
return c; | |
} | |
} | |
function distortByFunction(string, fn){ | |
if(fn == null){ | |
fn = squared; | |
} | |
//Scaled x value. If string has 5 characters, the x values will be 0, .2, .4, .6, and .8 | |
var xScale = 1 / string.length; | |
var distortedStr = ''; | |
for(var i=0; i<string.length; i++){ | |
var p = fn(xScale * i); | |
distortedStr += distortChar(string[i], p); | |
} | |
return distortedStr; | |
} | |
var distFns = { | |
constant: function(x){ | |
return 50; | |
}, | |
linear: function(x){ | |
return x; | |
}, | |
squared: function(x){ | |
return Math.pow(x,2); | |
}, | |
reverseSquared: function(x){ | |
return 1 - Math.pow(x,.5); | |
} | |
}; | |
var textToDistort = prompt('Enter text to distort'); | |
var distFnName = prompt('Enter a distortion function (constant, linear, squared, or reverseSquared) or leave blank for squared'); | |
var distFn; | |
if(distFns[distFn]){ | |
distFn = distFns[distFn]; | |
} else { | |
distFn = distFns['squared']; | |
} | |
alert(distortByFunction(textToDistort,distFn)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment