Last active
February 23, 2017 08:32
-
-
Save quant61/235882bd2ec0ca134daaf3748111b9b0 to your computer and use it in GitHub Desktop.
getting javascript value of random type
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
// special Javascript values | |
const specials = [null, true, false, undefined, NaN, 1/0, -1/0, -0]; | |
function getMixValue(){ | |
return randIndex([ | |
randSpecial, | |
randInt, | |
randFloat, | |
randStr, | |
randArray, | |
randObject, | |
])(); | |
} | |
function randIndex(array){ | |
return array[Math.random()*array.length|0]; | |
} | |
function randSpecial(){ | |
return specials[(Math.random()*Math.random()*specials.length)|0]; | |
} | |
function randInt(){ | |
return Math.random()*Math.pow(2,32)|0; | |
} | |
function randFloat(){ | |
return Math.random()/Math.random() - Math.random()/Math.random(); | |
} | |
function randChar(){ | |
return String.fromCharCode(32+ Math.random()*64); | |
} | |
function randStr(avgLen = 5){ | |
var str = ''; | |
while(Math.random() > 1/(avgLen+1)){ | |
str += randChar(); | |
} | |
return str; | |
} | |
function randArray(avgLen = 2){ | |
var arr = []; | |
while(Math.random() > 1/(avgLen+1)){ | |
arr.push(getMixValue()); | |
} | |
return arr; | |
} | |
function randKey(){ | |
return randChar() + randStr(8); | |
} | |
function randObject(avgLen = 2){ | |
var obj = {}; | |
while(Math.random() > 1/(avgLen+1)){ | |
obj[randKey()] = getMixValue(); | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment